QT中獲取選中的radioButton的兩種方法(動態取得控件的objectName之后,對名字進行比較)


QT中獲取選中的radioButton的兩種方法

 

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     }
復制代碼

兩種方法具有同樣的效果。

http://www.cnblogs.com/csuftzzk/archive/2013/01/14/2859320.html

 

QT中根據ID設置radio按鈕

 

前面提到,有兩種方法可以提取到radio按鈕組中當前被選中的按鈕(看這里)。這一篇中,我們根據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);
 
          
    QRadioButton* pbtn = qobject_cast<QRadioButton*>(ui->BG->button(0));
    QMessageBox::information(this, "Warning", pbtn->objectName(), QMessageBox::Ok);
在這個簡單的示例中,注意一些變量:radioButton, radioButton_2, radioButton_3是三個QRadioButton類型的控件變量,BG是QButtonGroup類型的變量。
我們首先使用QButtonGroup的類方法setId設置好各個radioButton的ID。這一步是必要的,因為默認的情況下其ID是不確定的。如果不設置的話,后來的代碼將會導致程序崩潰。setChecked()方法設置第一個radioButton為默認選中。
第二步中,我們通過ui->BG->button(ID)來選中指定ID的按鈕。注意,button()函數返回的是QAbstractionButton類型的指針。我們用qobject_cast<>來將其轉換為QRadioButton類型的指針。這個轉換是可行的,因為QRadioButton是QAbstractionButton的子類。至此,通過ID獲取選中狀態的RadioButton過程完成。
注:使用QT Creator進行UI設計時,沒有QButtonGroup類型的控件直接使用的。不過,有另外一種解決辦法:將要成組的radioButton一起選中,然后右鍵選擇“指定到按鈕組”,新建一個按鈕組並命名即可。當然也可以用代碼進行手動添加。



http://www.cnblogs.com/csuftzzk/archive/2013/01/14/2859846.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM