开发者

How to determine type of widget in a qtable cell?

I have created a QTable with lots of gui elements like comboBoxes and checkBoxes in various cells. I am able to access these elements by creating pointers to them. Wh开发者_开发技巧at I want to know is, is there any way to know what type of widget(comboBox or checkBox) a cell is having?


Check out the answers to this question. The accepted answer gets the class name (as a const char*) from the widget's meta-object like so:

widget->metaObject()->className();

There's another answer that suggests using C++'s type management, but that sounds a lot less wieldly (more unwieldy?).


I would suggest using qobject_cast https://doc.qt.io/qt-5/qobject.html#qobject_cast

It works like dynamic_cast but is a little better since it can make some Qt specific assumptions (doesn't depend on RTTI).

You can use it like this:

if(QPushButton *pb = qobject_cast<QPushButton*>(widget)) {
    // it's a "QPushButton", do something with pb here
}
// etc


You can write following utility functions:

bool IsCheckBox(const QWidget *widget)
{
   return dynamic_cast<const QCheckBox*>(widget) != 0;
}
bool IsComboBox(const QWidget *widget)
{
   return dynamic_cast<const QComboBox*>(widget) != 0;
}

Or maybe, you can use typeid to determine the runtime type of the object in the cell.

EDIT:

As @Evan noted in the comment, you can also use qobject_cast to cast the object, instead of dynamic_cast. See the examples here.


You can use QObject::className() to get the type of the widget.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜