Qt:QButtonGroup ゝ一世哀愁。 2023-01-12 11:46 90阅读 0赞 1、新建一个QtGUI应用,基类选择QWidget,取消创建界面,添加资源文件 2、widget.h中 #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QCheckBox> #include <QButtonGroup> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private: QButtonGroup *chk_group[2]; QCheckBox *exclusive[3]; QCheckBox *non_exclusive[3]; private slots: void chkChanged(); }; #endif // WIDGET_H widget.cpp中 #include "widget.h" #include <QDebug> #include <QString> Widget::Widget(QWidget *parent) : QWidget(parent) { QString str1[3] = {"游戏", "Offices", "Develop"}; QString str2[3] = {"P&rogramming", "Q&t", "O&S"}; chk_group[0] = new QButtonGroup(this); chk_group[1] = new QButtonGroup(this); int xpos = 30; int ypos = 30; for(int i = 0; i < 3; ++i){ exclusive[i] = new QCheckBox(str1[i], this); //可以在多个项目中多选 exclusive[i]->setGeometry(xpos, ypos, 100, 30); chk_group[0]->addButton(exclusive[i]); //分组 non_exclusive[i] = new QCheckBox(str2[i], this); non_exclusive[i]->setGeometry(xpos + 120, ypos, 100, 30); chk_group[1]->addButton(exclusive[i]); connect(non_exclusive[i], SIGNAL(clicked()), this, SLOT(chkChanged())); ypos += 40; } chk_group[0]->setExclusive(false); //单选 chk_group[1]->setExclusive(true); //多选 exclusive[0]->setIcon(QIcon(":resources/browser.png")); exclusive[1]->setIcon(QIcon(":resources/calendar.png")); exclusive[2]->setIcon(QIcon(":resources/chat.png")); non_exclusive[0]->setIcon(QIcon(":resources/editor.png")); non_exclusive[1]->setIcon(QIcon(":resources/mail.png")); non_exclusive[2]->setIcon(QIcon(":resources/users.png")); } Widget::~Widget() { } void Widget::chkChanged() { for(int i = 0 ; i < 3 ; i++) { if(non_exclusive[i]->checkState()) { qDebug("checkbox %d selected ", i+1); } } } ![215ed9e7d8bf5330caa93aac082c2c67bea.jpg][] [215ed9e7d8bf5330caa93aac082c2c67bea.jpg]: /images/20221119/e800fa93825c4930b35bedd5628c70c5.png
还没有评论,来说两句吧...