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;
}
which works well enough, but maybe there is a standard Qt function or way to do it?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With