Get index of checked switch in group

I have several switches in a group, is there a way to get the index of the current item?

enter image description here

I am using this code now:

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 a way to do this?

+5
source share
1 answer

This is an example of using a QButtonGroup .

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

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

When you use the Qt constructor to design your form, you can group the buttons by selecting them and choosing Assign to Button Group> New Button Group in the context menu. But I think that you cannot manually assign identifiers to buttons in a group. Instead, use QButtonGroup::setId(button, id) after setupUI to change the automatically assigned identifiers. (They are a bit confusing, considering minus s -2, and I don’t know how the designer chooses the order exactly, so I would not recommend depending on this order.)

+10
source

Source: https://habr.com/ru/post/1236352/


All Articles