萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> QT中獲取選中的radioButton的兩種方法

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

  方法一:采用對象名稱進行獲取

  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;

  }

copyright © 萬盛學電腦網 all rights reserved