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. What I want to know is, is there any way to know what type of widget
(comboBox
or checkBox
) a cell is having?
Asked
Active
Viewed 1.2k times
11
4 Answers
16
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?).

AAEM
- 1,837
- 2
- 18
- 26

Xavier Holt
- 14,471
- 4
- 43
- 56
-
The problem is that it is most likely much slower, due to traversal of the hirarchy. – Xeo Jun 01 '11 at 18:40
-
@Xeo - What would make this slow? A smart compiler should be able to optimize out the function calls, leaving you with a mere two pointer dereferences. – Xavier Holt Jun 01 '11 at 18:57
-
I meant the `dynamic_cast` or `typeid` approach. :) – Xeo Jun 01 '11 at 18:57
8
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

Vaidotas Strazdas
- 686
- 3
- 14

Evan Teran
- 87,561
- 32
- 179
- 238
1
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.

Vaidotas Strazdas
- 686
- 3
- 14

Nawaz
- 353,942
- 115
- 666
- 851
-
better to use `qobject_cast`. It is faster, doesn't depend on RTTI and works across library boundaries. – Evan Teran Jun 01 '11 at 18:49