方法一:采用对象名称进行获取
QRadioButton* pbtn = qobject_cast(ui->BG->checkedButton());
QString name = pbtn->objectName();
if(!QString::compare(name, "radioButton"))
{
QMessageBox::information(this, "Tips", "red chosed!", QMessageBox::Ok);
}
else if(!QString::compare(name, "radioButton_2"))
{
QMessageBox::information(this, "Tips", "blue chosed!", QMessageBox::Ok);
}
else
{
QMessageBox::information(this, "Tips", "black chosed!", QMessageBox::Ok);
}
该代码片段中,首先使用qobject_cast将checkedButton()函数返回的QAbstractionButton转换为其子类类型QRadioButton.然后,获取被选中按钮的对象名。这可以通过获取objectName这个属性获取。再稍作判断即可得知结果。注:BG是手动添加的QGroupButton类型,radioButton和radioButton_2,radioButton_3都是UI中添加的radioButton控件。
方法二:通过button的ID来获取
位于构造函数中的代码(初始选中第一个按钮):
ui->BG->setId(ui->radioButton, 0);
ui->BG->setId(ui->radioButton_2, 1);
ui->BG->setId(ui->radioButton_3, 2);
ui->radioButton->setChecked(true);
响应信号的槽函数或其他函数中的代码:
int a = ui->BG->checkedId();
switch(a)
{
case 0:
QMessageBox::information(this, "Tips", "Red chosed!", QMessageBox::Ok);
break;
case 1:
QMessageBox::information(this, "Tips", "blue chosed!", QMessageBox::Ok);
break;
case 2:
QMessageBox::information(this, "Tips", "black chosed!", QMessageBox::Ok);
break;
default:
break;
}