Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

9.4 Q_OBJECT and moc: A Checklist

QObject supports features not normally available in C++ objects.

  • Children (see the first two sections of Chapter 9)
  • Signals and slots (see Section 9.3.3)
  • MetaObjects, metaproperties, metamethods (see Chapter 15)
  • qobject_cast (see Section 15.3)

These features are only possible through the use of generated code. The Meta Object Compiler, moc, generates additional functions for each QObject-derived class that uses the macro. Generated code can be found in files with names moc_filename.cpp.

This means that some errors from the compiler/linker may be confuscated5 when moc is not able to find or process your classes. To help ensure that moc processes each of your QObject-derived classes, here are some guidelines for writing C++ code and qmake project files.

  • Each class definition should go in its own .h file.
  • Its implementation should go in a corresponding .cpp file.
  • The header file should be "#ifndef wrapped" to avoid multiple inclusion.
  • Each source (.cpp) file should be listed in the SOURCES variable of the project file, otherwise it will not be compiled.
  • The header file should be listed in the HEADERS variable of the .pro file. Without this, moc will not preprocess the file.
  • The Q_OBJECT macro must appear inside the class definition, so that moc will know to generate code for it.
  • + Share This
  • 🔖 Save To Your Account