判断QButtonGroup中哪个QRadioButton被选中

转载自http://qimo601.iteye.com/blog/1435285

T qobject_cast ( QObject * object )

如果object是T类型或者它的子类,就可以把object返回成T类型对象。否则返回0。

类T必须是QObject的子类,而且必须声明宏:Q_OBJECT

Example:

 

Cpp代码 复制代码  收藏代码
  1. QObject *obj = new QTimer;          // QTimer inherits QObject   
  2.   
  3.  QTimer *timer = qobject_cast<QTimer *>(obj);   
  4.  // timer == (QObject *)obj   
  5.   
  6.  QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);   
  7.  // button == 0  
QObject *obj = new QTimer;          // QTimer inherits QObject

 QTimer *timer = qobject_cast<QTimer *>(obj);
 // timer == (QObject *)obj

 QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
 // button == 0


问题判断QButtonGroup中哪个QRadioButton被选中

   方法1、可以通过对象名称去判断

 

Cpp代码 复制代码  收藏代码
  1.   QAbstractButton *radioButton = qobject_cast<QAbstractButton *> (ui.buttonGroup_1->checkedButton());   
  2.   
  3.  //ui.buttonGroup_1->checkedButton() 返回一个QRadioButton对象   
  4. //将它转换成QAbstractButton   
  5.   
  6. //判断QButtonGroup中哪个QRadioButton被选中,通过对象名称去判断   
  7. if(QString::compare(radioButton->objectName(), "topTubePositionRadio", Qt::CaseSensitive))   
  8.     tubePosition = 0;   
  9. else if(QString::compare(radioButton->objectName(), "bottomTubePositionRadio", Qt::CaseSensitive))   
  10.     tubePosition = 1;   
  11. else if (QString::compare(radioButton->objectName(), "lateralTubePositionRadio", Qt::CaseSensitive))   
  12.     tubePosition = 2;  
     QAbstractButton *radioButton = qobject_cast<QAbstractButton *> (ui.buttonGroup_1->checkedButton());

    //ui.buttonGroup_1->checkedButton() 返回一个QRadioButton对象
   //将它转换成QAbstractButton

   //判断QButtonGroup中哪个QRadioButton被选中,通过对象名称去判断
   if(QString::compare(radioButton->objectName(), "topTubePositionRadio", Qt::CaseSensitive))
       tubePosition = 0;
   else if(QString::compare(radioButton->objectName(), "bottomTubePositionRadio", Qt::CaseSensitive))
       tubePosition = 1;
   else if (QString::compare(radioButton->objectName(), "lateralTubePositionRadio", Qt::CaseSensitive))
       tubePosition = 2;

 

  方法2:通过checkedId去判断

首先需要在界面被激活初始化设置buttonGroup中的Id

 

Cpp代码 复制代码  收藏代码
  1. ui.buttonGroup_1->setId(ui.topTubePositionRadio,0);//topTubePositionRadio的Id设为0   
  2. ui.buttonGroup_1->setId(ui.bottomTubePositionRadio,1);   
  3. ui.buttonGroup_1->setId(ui.lateralTubePositionRadio,2);  
ui.buttonGroup_1->setId(ui.topTubePositionRadio,0);//topTubePositionRadio的Id设为0
ui.buttonGroup_1->setId(ui.bottomTubePositionRadio,1);
ui.buttonGroup_1->setId(ui.lateralTubePositionRadio,2);

 

然后在你想获取哪个radioButton被选中时直接获取checkedId值,最后判断一下这个Id值就可以了。

quint16 a = ui.buttonGroup_1->checkedId();

 

很纳闷为啥QtDesigner中没有界面直接赋给这个radioButton,Id值?????或许是没有必要吧,第一种方法也可以。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值