Qt的Radio Button(单选按钮)
1 在UI界面中加入控件
2 对QRadioButton控件进行分组
QRadioButton的分组有多重方法,如采用组合框、QWidge等,下面介绍采用QButtonGroup方法来实现分组,好处是不影响QRadioButton在界面上的显示(组合框分组方式会在界面上出现组合框,要以自己的需要选择),以及方便ID的设置。
添加头文件
#include <QButtonGroup>
#include <QDebug>
声明QButtonGroup变量
private:
QButtonGroup *groupButton1;
QButtonGroup *groupButton2;
在窗体构造函数中初始化QButtonGroup,把相应的QRadioButton添加进来并设置ID
groupButton1=new QButtonGroup(this);
groupButton1->addButton(ui->apple_radioButton,0);
groupButton1->addButton(ui->banan_radioButton,1);
groupButton1->addButton(ui->pear_radioButton,2);
ui->apple_radioButton->setChecked(true); //默认选中apple_radioButton
groupButton2=new QButtonGroup(this);
groupButton2->addButton(ui->potato_radioButton,0);
groupButton2->addButton(ui->greenpepper_radioButton,1);
groupButton2->addButton(ui->spinach_radioButton,2);
ui->greenpepper_radioButton->setChecked(true);
3 多个QRadioButton控件响应同一个槽函数
在头文件中声明槽函数
public slots:
void slots_fruits();
void slots_vegetables();
在窗体构造函数中绑定信号和槽函数
//绑定信号和槽函数
connect(ui->apple_radioButton,SIGNAL(clicked(bool)),
this,SLOT(slots_fruits()));
connect(ui->banan_radioButton,SIGNAL(clicked(bool)),
this,SLOT(slots_fruits()));
connect(ui->pear_radioButton,SIGNAL(clicked(bool)),
this,SLOT(slots_fruits()));
//绑定信号和槽函数
connect(ui->potato_radioButton,SIGNAL(clicked(bool)),
this,SLOT(slots_vegetables()));
connect(ui->greenpepper_radioButton,SIGNAL(clicked(bool)),
this,SLOT(slots_vegetables()));
connect(ui->spinach_radioButton,SIGNAL(clicked(bool)),
this,SLOT(slots_vegetables()));
槽函数的实现
QRadioButton的槽函数中,不需要逐个检查QRadioButton控件状态,仅仅通过groupButton1->checkedId()来获知哪一个QRadioButton控件被选中,其返回被选中控件的ID值。
void MainWindow::slots_fruits()
{
qDebug()<<"fruits"<<endl;
switch(groupButton1->checkedId())
{
case 0:
qDebug() <<"apple"<<endl;
break;
case 1:
qDebug() <<"banan_radioButton"<<endl;
break;
case 2:
qDebug() <<"pear_radioButton"<<endl;
break;
}
}
void MainWindow::slots_vegetables()
{
qDebug()<<"vegetables"<<endl;
switch(groupButton2->checkedId())
{
case 0:
qDebug() <<"potato_radioButton"<<endl;
break;
case 1:
qDebug() <<"greenpepper_radioButton"<<endl;
break;
case 2:
qDebug() <<"spinach_radioButton"<<endl;
break;
}
}
运行结果
参考资料
https://blog.csdn.net/CXP2205455256/article/details/44956051