QT中要獲取radioButton組中被選中的那個按鈕,可以采用兩種如下兩種辦法進行:
方法一:采用對象名稱進行獲取
代碼:
1 QRadioButton* pbtn = qobject_cast<QRadioButton*>(ui->BG->checkedButton()); 2 QString name = pbtn->objectName(); 3 if(!QString::compare(name, "radioButton")) 4 { 5 QMessageBox::information(this, "Tips", "red chosed!", QMessageBox::Ok); 6 } 7 else if(!QString::compare(name, "radioButton_2")) 8 { 9 QMessageBox::information(this, "Tips", "blue chosed!", QMessageBox::Ok); 10 } 11 else 12 { 13 QMessageBox::information(this, "Tips", "black chosed!", QMessageBox::Ok); 14 }
該代碼片段中,首先使用qobject_cast將checkedButton()函數返回的QAbstractionButton轉換為其子類類型QRadioButton.然后,獲取被選中按鈕的對象名。這可以通過獲取objectName這個屬性獲取。再稍作判斷即可得知結果。注:BG是手動添加的QGroupButton類型,radioButton和radioButton_2,radioButton_3都是UI中添加的radioButton控件。
方法二:通過button的ID來獲取
代碼:
位於構造函數中的代碼(初始選中第一個按鈕):
1 ui->BG->setId(ui->radioButton, 0); 2 ui->BG->setId(ui->radioButton_2, 1); 3 ui->BG->setId(ui->radioButton_3, 2); 4 ui->radioButton->setChecked(true);
這一步是必須的,必須先設置好radiobutton組中各個按鈕的ID值,否則會導致程序崩潰。
響應信號的槽函數或其他函數中的代碼:
1 int a = ui->BG->checkedId(); 2 switch(a) 3 { 4 case 0: 5 QMessageBox::information(this, "Tips", "Red chosed!", QMessageBox::Ok); 6 break; 7 case 1: 8 QMessageBox::information(this, "Tips", "blue chosed!", QMessageBox::Ok); 9 break; 10 case 2: 11 QMessageBox::information(this, "Tips", "black chosed!", QMessageBox::Ok); 12 break; 13 default: 14 break; 15 }
兩種方法具有同樣的效果。