tags:

views:

91

answers:

4

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.

A: 

If you want to use signals/slots you MUST include the Q_OBJECT macro and derive the class from QObject.

Otherwise you can leave it out, but it doesn't do any harm to include it in all the Qt gui classes

Martin Beckett
A: 

Well the first part is pretty clear as you probably already know.. signals and slots, the rest of the Meta-object system is a little lesser known. Perhaps one of the more useful features is dynamic properties. Although these have many uses, I used them to take advantage of Qt's animation system QPropertyAnimation.

There's a little more info about the meta-object system here: http://doc.qt.nokia.com/4.6/metaobjects.html

I think the bottom line is, if you inherit from the QObject hierarchy, throw in the Q_OBJECT macro regardless. It's simple to do and will save you from some potentially baffling problems down the road.

Arnold Spence
+6  A: 

Actually, you have to use Q_OBJECT macro, for any classes that you derive from QOject.

Besides Signals and slots, Q_OBJECT macro enables to retrieve the Meta Object information that is associated with the object..

Check out the docs...

From the docs itself,

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.

You can omit it for time sake, but in the long run you may have to use some of the Meta object features.. Say for e.g you may have to use

QString QObject::tr ( const char * sourceText, const char * disambiguation = 0, int n = -1 ) [static]

In such cases, you have to declare the Q_Object macro. So, it is better now to use the Q_OBJECT macro instead of thinking that someone will do it whenever they need it..

or else, if you don't need the Q_OBJECT macro, have normal C++ classes that doesn't get derived from QObject... So that it doesn't use any Meta object functionality.

Hope it helps...

liaK
A: 

What @liaK said is correct (in short: you should always use the Q_OBJECT macro in any class that derives from QObject).

One thing that I haven't seen highlighted is that if you don't explicitly put the Q_OBJECT macro then using the sometimes very handy qobject_cast won't work!!!

lucabox