8.4 Q_OBJECT and moc: A checklist

来源:互联网 发布:淘宝卖家分类怎么设置 编辑:程序博客网 时间:2024/04/30 09:49
8.4 Q_OBJECT and moc: A checklist
QObject supports features not normally available in C++ objects:
• Signals and Slots ( Section 8.5 )
• MetaObjects, MetaProperties, MetaMethods ( Chapter 12 , “Meta Objects,
Properties, and Reflective Programming”)
• qobject_cast ( Section 12.2 )
Some of 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 Q_OBJECT macro. Generated code can be found in files with names
moc_filename.cpp .
This means that some errors from the compiler/linker may be confuscated 8 when
moc cannot find or process a class in the project. To help ensure that moc processes
each QObject -derived class in the project, following 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 “wrapped” (e.g., with #ifndef ) to avoid multiple
inclusion.
• Each .cpp file should be listed in the SOURCES variable of the project file;
otherwise it will not be compiled.
• Each 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 of each QObject
derived header file so that moc knows to generate code for it.
NOTE
Because each Q_OBJECT macro generates code, it needs to be preprocessed by moc.
moc works under the assumption that you are only deriving from QObject once and, further,
that QObject is the first base class in the list of base classes. If you accidentally inherit from
QObject more than once, or if it is not the first base class in the inheritance list, you may produce
strange errors in the moc-generated code.
8 confusing + obfuscated
8.5 Signals and Slots 275
NOTE
If you define a QObject -derived class, build an application, realize that you need to add
the Q_OBJECT macro to the class definition, and add it after the project was built with an old
Makefile , you must then rerun qmake to update the Makefile .
make is not smart enough to add the moc step on such files to your Makefile otherwise. A
“clean rebuild” does not fix this problem usually. This is an issue that often causes headaches for
inexperienced Qt developers. For more information about this error message, see Section C.3.1.
0 0
原创粉丝点击