[Qt-interest] Comparing two QMetaObjects

Oliver.Knoll at comit.ch Oliver.Knoll at comit.ch
Mon Feb 7 15:23:20 CET 2011


On 2011-02-07 ITS-CMT-SL-SFR-FIN-DEV Knoll Oliver, ITS-CMT-SL-SFR-FIN-DEV wrote:

> ... Usually that is done with
> http://doc.qt.nokia.com/4.7/qobject.html#inherits (which makes use of the meta
> objects), as in:
> 
>   if (a->inherits(A::staticMetaObject().className()) {...}

The comment from Thiago reminded me of a very crucial thing: EVERY object in the class hierarchy has to have the Q_OBJECT macro in their header/class declaration! Even if your own instance does not make direct use of the Qt object system, such as emitting signals or connecting to other signals or defining slots. The Q_OBJECT macro makes sure that the proper "Runtime Type Information" is added to the class instances.

Or in other words:

Class MyClass : public QObject
{
  // we forgot to use the Q_OBJECT macro here! BAD!
public:
  // no use of slots or signals here
  ...
};

MyClass myClass;

if (myClass.inherits("QObject")) {...}

This test succeeds as expected: 'myClass' if of type "MyClass", which inherits from QObject.

BUT:

if (myClass.inherits("MyClass")) {...}

would fail, because myClass.metaObject().className() would return "QObject" and NOT the (expected) "MyClass" value: no proper meta object information is generated for class MyClass, due to the missing Q_OBJECT declaration!

Note that QObject::inherits() is also supposed to return true if the instance "is a" instance of the given class ("including inheritance"), as in:

 QTimer *timer = new QTimer;         // QTimer inherits QObject
 timer->inherits("QTimer");          // returns true
 timer->inherits("QObject");         // returns true

p.s. Yes, I fell into this "trap" once, too... ;)

Cheers, Oliver
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22




More information about the Qt-interest-old mailing list