views:

1692

answers:

2

I just started using QT and noticed that all the example class definitions have the macro Q_OBJECT as the first line. What is the purpose of this preprocessor macro?

+10  A: 

From the Qt documentation:

The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions.

The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.

Stu Mackellar
+1  A: 

It simply tells the pre-compiler that this class has gui elements and needs to be run through the 'moc' you only need to add this to classes that use the signal/slot mechanism.
But it will be quietly ignored in any other classes - it just adds to the build time.

Martin Beckett
Minor nit-pick... a class doesn't have to have GUI elements to benefit from and/or need the Q_OBJECT macro. Basically, anything that inherits from QObject and needs access to the meta-data needs it. (Meta-data includes signals/slots.)
Caleb Huitt - cjhuitt