Is there a way to have all radion buttons be unchecked

后端 未结 2 621
你的背包
你的背包 2021-02-07 04:20

I have a QGroupBox with a couple of QRadioButtons inside of it and in certain cases I want all radio buttons to be unchecked. Seems that this is not possible when a selection h

2条回答
  •  滥情空心
    2021-02-07 05:21

    You can achieve this effect by temporarily turning off auto exclusivity for all your radio buttons, unchecking them, and then turning them back on:

    QRadioButton* rbutton1 = new QRadioButton("Option 1", parent);
    // ... other code ...
    rbutton1->setAutoExclusive(false);
    rbutton1->setChecked(false);
    rbutton1->setAutoExclusive(true);
    

    You might want to look at using QButtonGroup to keep things tidier, it'll let you turn exclusivity on and off for an entire group of buttons instead of iterating through them yourself:

    // where rbuttons are QRadioButtons with appropriate parent widgets
    // (QButtonGroup doesn't draw or layout anything, it's just a container class)
    QButtonGroup* group = new QButtonGroup(parent);
    group->addButton(rbutton1);
    group->addButton(rbutton2);
    group->addButton(rbutton3);
    
    // ... other code ...
    
    QAbstractButton* checked = group->checkedButton();
    if (checked)
    {
        group->setExclusive(false);
        checked->setChecked(false);
        group->setExclusive(true);
    }
    

    However, as the other answers have stated, you might want to consider using checkboxes instead, since radio buttons aren't really meant for this sort of thing.

提交回复
热议问题