11

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?

AAEM
  • 1,837
  • 2
  • 18
  • 26
rwik
  • 775
  • 2
  • 12
  • 27

4 Answers4

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
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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

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

BЈовић
  • 62,405
  • 41
  • 173
  • 273