注意:QCheckBox默认是多选,只要一组QCheckBox不在一个层级(就是在不同父节点下面),就可以变成互斥不受影响。
//用lambda表达式绑定信号槽
void (QButtonGroup::*buttonClicked)(QAbstractButton *) = &QButtonGroup::buttonClicked;
connect(group, buttonClicked, [=](QAbstractButton *but) {
qDebug() << but->objectName() << "|" << but->isChecked();
});
//加组后默认变成单选
QButtonGroup *group = new QButtonGroup(this);
group->addButton(ui.checkBox);
group->addButton(ui.checkBox_2);
QRadioButton *pButton1 = new QRadioButton("QRadioButton001");
QRadioButton *pButton2 = new QRadioButton("QRadioButton002");
QRadioButton *pButton3 = new QRadioButton("QRadioButton001");
//按钮组
QButtonGroup *pGroup = new QButtonGroup(this);
pGroup->setObjectName("group");
pGroup->addButton(pButton1);
pGroup->addButton(pButton2);
pGroup->addButton(pButton3);
//垂直布局器
QVBoxLayout *layout = new QVBoxLayout(this);
//遍历按钮组
for (const auto &it : pGroup->buttons())
{
layout->addWidget(it);
}
QPushButton *button = new QPushButton(QString::fromLocal8Bit("保存"),this);
connect(button, &QPushButton::clicked, [=]() {
//获取按钮组
QButtonGroup *pGroup = this->findChild<QButtonGroup *>("group");
if (pGroup != nullptr)
{
//获取按钮组的哪个按钮被点击
QRadioButton *but = dynamic_cast<QRadioButton *>(pGroup->checkedButton());
if (but != nullptr)
{
QMessageBox::information(this, "", but->text());
}
}
});
layout->addWidget(button);