本例程介绍QRadioButton的使用,包括QRadioButton的分组、多个QRadioButton控件响应同1个槽函数、QRadioButton的ID设置从而避免繁琐的判断。
1、在UI界面添加以下控件:
2、对QRadioButton控件进行分组
QRadioButton的分组有多重方法,如采取组合框、QWidge等,下面介绍采取QButtonGroup方法来实现分组,好处是不影响QRadioButton在界面上的显示(组合框分组方式会在界面上出现组合框,要以自己的需要选择),和方便ID的设置。
首先添加头文件:
#include <QButtonGroup>
声明
QButtonGroup变量
QButtonGroup *btnGroupFruits;
QButtonGroup *btnGroupVegetables;
在窗体构造函数中初始化
QButtonGroup,和把相应的QRadioButton添加进来并设置ID
btnGroupFruits = new QButtonGroup(this);
btnGroupFruits->addButton(ui->radioButton11, 0);
btnGroupFruits->addButton(ui->radioButton12, 1);
btnGroupFruits->addButton(ui->radioButton13, 2);
ui->radioButton11->setChecked(true);
btnGroupVegetables = new QButtonGroup(this);
btnGroupVegetables->addButton(ui->radioButton21, 0);
btnGroupVegetables->addButton(ui->radioButton22, 1);
btnGroupVegetables->addButton(ui->radioButton23, 2);
ui->radioButton21->setChecked(true);
3、多个
QRadioButton控件响应同1个槽函数
在头文件声明槽函数:
public slots:
void onRadioClickFruits();
void onRadioClickVegetables();
在窗体构造函数中绑定信号与槽:
connect(ui->radioButton11, SIGNAL(clicked()), this, SLOT(onRadioClickFruits()));
connect(ui->radioButton12, SIGNAL(clicked()), this, SLOT(onRadioClickFruits()));
connect(ui->radioButton13, SIGNAL(clicked()), this, SLOT(onRadioClickFruits()));
connect(ui->radioButton21, SIGNAL(clicked()), this, SLOT(onRadioClickVegetables()));
connect(ui->radioButton22, SIGNAL(clicked()), this, SLOT(onRadioClickVegetables()));
connect(ui->radioButton23, SIGNAL(clicked()), this, SLOT(onRadioClickVegetables()));
槽函数的实现:
QRadioButton的槽函数中,不需要逐一检查QRadioButton控件状态,仅仅通过btnGroupFruits->checkedId()来获知哪个QRadioButton控件被选中,其返回被选中控件的ID值。
void MainWindow::onRadioClickFruits()
{
switch(btnGroupFruits->checkedId())
{
case 0:
qDebug() << QString::fromLocal8Bit("苹果");
break;
case 1:
qDebug() << QString::fromLocal8Bit("西红柿");
break;
case 2:
qDebug() << QString::fromLocal8Bit("芒果");
break;
}
}
void MainWindow::onRadioClickVegetables()
{
switch(btnGroupVegetables->checkedId())
{
case 0:
qDebug() << QString::fromLocal8Bit("土豆");
break;
case 1:
qDebug() << QString::fromLocal8Bit("青椒");
break;
case 2:
qDebug() << QString::fromLocal8Bit("菠菜");
break;
}
}
以下是程序运行结果: