当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - 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?

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: