The documentation states that:
The Q_OBJECT macro must appear in the
private section of a class definition
that declares its own signals and
slots or that uses other services
provided by Qt’s meta-object system.
But exactly what does that mean? On which QObject-derived classes can I safely omit it? Will problems arise if you omit Q_OBJECT on a QObject-derived class, and then inherit from that one? Basically I would like a little more information on when I can omit it from my Qt classes.
You should use the
Q_OBJECTmacro for any non-templated classes that derive fromQObject.Besides signals and slots, the
Q_OBJECTmacro provides the meta object information that is associated with given class.As stated in the documentation:
Suppose we have the following class:
Without
Q_OBJECT, the following metaobject system features (among others) will not work forClass:qobject_cast<Class>()– due to missing metadataQObject::tr()– due to missing metadataslots and invokables first declared in
Class, when invoked or looked up by name – none ofQMetaObjectmethods will work for these methods, neither will the Qt 4connect– due to missing metadatasignals – since
mocwon’t generate their implementations and the code won’t compile.You can omit it, of course, but if you ever use these features, you’ll need to remember to put the macro into the class’s declaration. This is a rather brittle practice and best avoided. The savings are not worth it. So, don’t wait – add the
Q_OBJECTmacro to every class that derives fromQObjectas a matter of coding policy.The
Q_OBJECTmacro should never be used on classes that don’t derive fromQObject. To add invokables and properties to such classes, use theQ_GADGETmacro instead.