转载自http://qimo601.iteye.com/blog/1435285
如果object是T类型或者它的子类,就可以把object返回成T类型对象。否则返回0。
类T必须是QObject的子类,而且必须声明宏:Q_OBJECT
Example:
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、可以通过对象名称去判断
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
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值?????或许是没有必要吧,第一种方法也可以。