有没有办法让所有单选按钮都没有选中

时间:2009-11-13 20:16:03

标签: qt

我有一个QGroupBox,里面有几个QRadioButtons,在某些情况下我想要取消选中所有单选按钮。似乎在进行选择时无法做到这一点。你知道我可以做到这一点的方法,还是应该添加一个隐藏的单选按钮并检查它以获得所需的结果。

2 个答案:

答案 0 :(得分:30)

您可以通过暂时关闭所有单选按钮的自动排他性,取消选中它们,然后重新打开它们来实现此效果:

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

您可能希望使用QButtonGroup来保持整洁,它可以让您打开和关闭整个按钮组的排他性,而不是自己迭代它们:

// 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);
}

但是,正如其他答案所述,您可能需要考虑使用复选框,因为单选按钮并不是真正意义上的。

答案 1 :(得分:0)

如果使用QGroupBox对按钮进行分组,则不能使用setExclusive(false)函数取消选中已选中的RadioButton。您可以在QT文档的QRadioButton部分中阅读有关此内容的信息。因此,如果您想重置按钮,可以尝试执行以下操作:

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);
}

您可以禁用ButtonGroup的Exclusive属性以重置与ButtonGroup相关联的所有按钮,然后可以启用Exclusive属性,这样将无法进行多个按钮检查。

相关问题