Qt - iterating through QRadioButtons

女生的网名这么多〃 提交于 2020-01-04 04:12:10

问题


I have a group project for school that I am working on. A member of my group has created a window that has ~75 radio buttons. I want to force all of them to be "clear" or "unchecked" on a button press.

Does anyone know a good way to go about doing this? I have been looking into QObjectList but I can't simply do QObjectList *children = new QObjectList(ui->groupBox->children()); and loop them using a for loop as QObjectList does not appear to have a next method..

I have also tried to do something like

QObjectList *children = new QObjectList(ui->groupBox->children());
for(QObject *iterator = children.first(); iterator!=NULL; children.pop_front()){
    iterator = children.first();
    iterator->at(0)->setCheckabled(false);
}

But because iterator is a QObject, setCheckable does not exist like on a radio button.

Thoughts/hints would be appreciated.

Edit: I'll even take a hint on a way to iterate through variables with similar names. For instance, all of my radiobuttons are named RadioButton_1, RadioButton_2, etc.


回答1:


Use a QButtonGroup, set it to exclusive (then only one radiobutton will be checked at a time). It also gives you the currently checked button, in case you want to uncheck it, too. (to have no checked buttons at all).

Also note that what you probably want to modify is the "checked" property, not "checkable" (where false means that the button can't be checked/unchecked at all).




回答2:


If you don't like using QButtonGroup (too much setup effort or for whatever other reasons), then use some iteration like this:

QListIterator<QObject *> i(ui->groupBox->children());
while (i.hasNext())
{
    QRadioButton* b = qobject_cast<QRadioButton*>( i.next() );
    if (b > 0 && b->isChecked()) {
        b->setAutoExclusive(false);
        b->setChecked(false);
        b->setAutoExclusive(true);
    }
}

Most likely you need to manipulate autoexclusive (as done in the above code block) to have all radio buttons unchecked (see also @Kristofer's answer: https://stackoverflow.com/a/9375491/1150303)



来源:https://stackoverflow.com/questions/5598487/qt-iterating-through-qradiobuttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!