开始看qt时一直没弄明白如何分组不同的单选按钮
总是用一个groupbox来把他们圈起来,但实际上不用如此,尽管这样作也不赖
从qt designer生成的代码显示是通过不同的widget来派生新的radiobutton,
但显然qt还是为手写代码提供了更简单的方式。
下面这段代码演示了如何使用buttongroup来完成这项工作
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
#include <QApplication>
#include <QWidget>
#include <QButtonGroup>
#include <QRadioButton>
#include <QVBoxLayout>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget *window = new QWidget;
window->setWindowTitle("QRadioButton");
window->resize(200, 100);
QVBoxLayout *windowLayout = new QVBoxLayout;
QRadioButton *radio1 = new QRadioButton("Linux OS");
QRadioButton *radio2 = new QRadioButton("Windows OS");
QButtonGroup *grp1=new QButtonGroup(window);
//组1
grp1->addButton(radio1);
grp1->addButton(radio2);
QRadioButton *radio3 = new QRadioButton("Server");
QRadioButton *radio4 = new QRadioButton("PC");
QButtonGroup *grp2=new QButtonGroup(window);
//组2
grp2->addButton(radio3);
grp2->addButton(radio4);
windowLayout->addWidget(radio1);
windowLayout->addWidget(radio2);
windowLayout->addWidget(radio3);
windowLayout->addWidget(radio4);
window->setLayout(windowLayout);
window->show();
return app.exec();
}