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

Trevor Boyd Smith picture Trevor Boyd Smith · Sep 2, 2009 · Viewed 74.3k times · Source

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?

Answer

Stu Mackellar picture Stu Mackellar · Sep 2, 2009

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.