一,QRadioButtonTest+ButtonGroup单选后提示消息
项目名称:QRadioButtonTest
运行结果:选中按钮后其他则无法继续选择,点击save后提示选择了那个按钮
在QRadioButtonTest.h头文件中添加槽函数
QRadioButtonTest.h
#pragma once
#include <QtWidgets/QWidget>
#include "ui_QRadioButtonTest.h"
class QRadioButtonTest : public QWidget
{
Q_OBJECT
public:
QRadioButtonTest(QWidget *parent = Q_NULLPTR);
public slots:
void save();
private:
Ui::QRadioButtonTestClass ui;
};
在QRadioButtonTest.cpp添加代码
#include "QRadioButtonTest.h"
#include <QRadioButton>
#include <QVBoxLayout>
#include <QButtonGroup>
#include <QPushButton>
#include <QMessageBox>
QRadioButtonTest::QRadioButtonTest(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
QRadioButton *rb1 = new QRadioButton("QRadioButton001");
QRadioButton *rb2 = new QRadioButton("QRadioButton002");
QRadioButton *rb3 = new QRadioButton("QRadioButton003");
//按钮组
QButtonGroup *group = new QButtonGroup(this);
group->setObjectName("group");
group->addButton(rb1);
group->addButton(rb2);
group->addButton(rb3);
//处置布局器
QVBoxLayout *vb = new QVBoxLayout(this);
//添加按钮组
for (int i = 0; i < group->buttons().size(); i++)
{
vb->addWidget(group->buttons()[i]);
}
//保存按钮
QPushButton *save = new QPushButton("save");
QObject::connect(save, SIGNAL(clicked()), this, SLOT(save()));
vb->addWidget(save);
}
void QRadioButtonTest::save()
{
//获取按钮组
QButtonGroup *group= this->findChild<QButtonGroup*>("group");
if (!group)return;
//获取被选中的按钮
QRadioButton *but = (QRadioButton *)group->checkedButton();
if (!but)return;
QMessageBox::information(this, "233", but->text());
}
运行结果
二,QComBox(下拉框)
首先创建项目QComBoxTest
在ui界面中选择combox
运行结果