How to determine type of widget in a qtable cell?
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
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?).
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.