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

The MOC (meta object compiler) converts the Q_OBJECT macro included header files in to C++ equivalent source code. It basically controls the signal-slot mechanism, and makes it understandable to the C++ compiler


It simply tells the pre-compiler that this class needs to be run through the 'moc', or Meta-Object Compiler, which adds extra hidden fields and functions to the class as well as parsing signals and slots. You only need to add this to classes that use the signal/slot mechanism or other Qt class-level features, such as introspection. You do not need to add Q_OBJECT to classes that only use standard C++ features.


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.

Tags:

C++

Qt

Macros