How to determine the type of widget in a qtable cell?

I created a QTable with many comboBoxes elements like comboBoxes and checkBoxes in different cells. I can access these elements by creating pointers for them. I want to know if there is a way to find out which widget ( comboBox or checkBox ) a cell has?

+8
c ++ qt4
source share
4 answers

Check the answers to this question . The accepted answer gets the class name (like const char* ) from the widget meta object as follows:

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

There is another answer that suggests using C ++ type control, but it sounds much less cumbersome (more cumbersome?).

+13
source share

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

It works like dynamic_cast but is slightly better, as it can make some specific assumptions of Qt (independent of RTTI).

You can use it like this:

 if(QPushButton *pb = qobject_cast<QPushButton*>(widget)) { // it a "QPushButton", do something with pb here } // etc 
+6
source share

You can write the 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 an object in a cell.

EDIT:

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

+1
source share

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

0
source share

All Articles