Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of checked radio button in group

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

enter image description here

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;
}

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

like image 373
sashoalm Avatar asked Nov 19 '15 16:11

sashoalm


1 Answers

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.)

like image 197
leemes Avatar answered Nov 01 '22 12:11

leemes