You should use the Q_OBJECT
macro for any non-templated classes that derive from QObject
.
Besides signals and slots, the Q_OBJECT
macro provides the meta object information that is associated with given class.
As stated in the documentation:
we strongly recommend that all subclasses of QObject use the Q_OBJECT macro regardless of whether or not they actually use signals, slots, and properties.
Suppose we have the following class:
class Class : public QObject {
public:
Class() {}
};
Without Q_OBJECT
, the following metaobject system features (among others) will not work for Class
:
qobject_cast<Class>()
- due to missing metadata
QObject::tr()
- due to missing metadata
slots and invokables first declared in Class
, when invoked or looked up by name - none of QMetaObject
methods will work for these methods, neither will the Qt 4 connect
- due to missing metadata
signals - since moc
won'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_OBJECT
macro to every class that derives from QObject
as a matter of coding policy.
The Q_OBJECT
macro should never be used on classes that don't derive from QObject
. To add invokables and properties to such classes, use the Q_GADGET
macro instead.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…