Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to check QObject derived class type in Qt

Tags:

types

qt

qobject

Lets say I have a two classes:

class A : public QObject {};
class B : public QObject {};

then I go

QObject *a = new A();
QObject *b = new B();

now, how do I make sure that "a" is an instance of class A, and "b" is an instance of class B?

currently I do something like this:

if (a->inherits(A::staticMetaObject.className())) {
...
} else if (a->inherits(A::staticMetaObject.className())) {
...

is there a better way?

like image 802
ak. Avatar asked Oct 08 '09 10:10

ak.


1 Answers

You can use qobject_cast<MyClass*>(instance) on QObject derived classes and check the return value. If instance cannot be cast to MyClass*, the return value will be NULL.

like image 171
erelender Avatar answered Oct 14 '22 19:10

erelender