Is there a way to have all radion buttons be unchecked

后端 未结 2 622
你的背包
你的背包 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:07

    If you're using QGroupBox to group buttons, you can't use the setExclusive(false) function to uncheck the checked RadioButton. You can read about it in QRadioButton section of QT docs. So if you want to reset your buttons, you can try something like this:

    QButtonGroup *buttonGroup = new QButtonGroup;
    QRadioButton *radioButton1 = new QRadioButton("button1");
    QRadioButton *radioButton2 = new QRadioButton("button2");
    QRadioButton *radioButton3 = new QRadioButton("button3");
    
    buttonGroup->addButton(radioButton1);
    buttonGroup->addButton(radioButton2);
    buttonGroup->addButton(radioButton3);
    
    if(buttonGroup->checkedButton() != 0)
    {
       // Disable the exclusive property of the Button Group
       buttonGroup->setExclusive(false);
    
       // Get the checked button and uncheck it
       buttonGroup->checkedButton()->setChecked(false);
    
       // Enable the exclusive property of the Button Group
       buttonGroup->setExclusive(true);
    }
    

    You can disable the exclusive property of the ButtonGroup to reset all the buttons associated with the ButtonGroup, then you can enable the Exclusive property so that multiple button checks won't be possible.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题