方法一:採用對象名稱進行擷取
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;
}