Get index of checked radio button in group
Asked Answered
V

1

16

I have several radio buttons in a group, is there a way to get the index of the currently checked item?

Right now I use this code:

int getCheckedRadioButton(QWidget *w)
{
    int ii = 0;
    foreach (QRadioButton *button, w->findChildren<QRadioButton*>()) {
        if (button->isChecked()) {
            return ii;
        }
        ii++;
    }
    return -1;
}

This works well enough, but maybe there is a standard Qt function or way to do it?

Verboten answered 19/11, 2015 at 16:20 Comment(0)
C
37

That's a use case for QButtonGroup.

Group your radio buttons with QButtonGroup if you haven't already. For each button, use QButtonGroup::addButton(button, id) to assign consecutive ids to your buttons, starting with zero.

Then, to receive the index of the button, use QButtonGroup::checkedId().

When you use the Qt designer to design your form, you can group buttons by selecting them and choosing "Assign to button group" > "New button group" from the context menu. But I think you cannot manually assign IDs to the buttons in the group. Instead, use QButtonGroup::setId(button, id) after setupUI in order to change the automatically assigned IDs. (They are kind of confusing, counting negative from -2 and I don't know how the designer chooses the order exactly, so I wouldn't recommend to depend on that order.)

Chantry answered 19/11, 2015 at 16:36 Comment(2)
Really excellent answer! The upvotes don't do it justice, so I thought I'd explicitly say thank you for writing it :)Sidecar
Ditto on the excellent answer. There is so much that is obtuse about Qt to the novice. Your answer kept me from doing more work.Novak

© 2022 - 2024 — McMap. All rights reserved.