What does the Q_OBJECT macro do? Why do all Qt objects need this macro?


Question

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?

1
119
4/7/2016 8:37:04 PM

Accepted Answer

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.

126
4/7/2016 8:48:08 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon