欢迎来到山村网

QT中获取选中的radioButton的两种方法

2019-03-02 09:46:02浏览:924 来源:山村网   
核心摘要:  方法一:采用对象名称进行获取  QRadioButton* pbtn = qobject_cast(ui-BG-checkedButton());  QString name = pbtn-obj

  方法一:采用对象名称进行获取

  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;

  }

(责任编辑:豆豆)
下一篇:

为什么软件程序员的价值总是被严重的低估

上一篇:

DOS中判断进程是否存在的方法

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com