Q_OBJECT 宏
Q_OBJECT 宏
Q_OBJECT可能是对Qt初学者来说最奇怪的东西了。
Qt QObject Class这样描述:
The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt's meta-object system.
一个类声明了自己的信号和槽或者使用了其他Qt's元对象系统,必须在它的private段包含Q_OBJECT宏。
class MyClass: public QObject
{
Q_OBJECT
public:
MyClass(QObject *parant = 0);
~MyClass();
signals:
void mySignal();
public slots:
void mySlot();
};
一个moc相关的文档中的解释:
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.元对象编译器moc是一个处理Qt's C++的扩展。
moc工具读入C++头文件后,如果它发现一个或多个类声明中包含有Q_OBJECT宏,它就产生一个C++源文件来为这些类包含meta-object代码。另外,meta-object代码对信号和槽、运行时类型信息,以及动态属性系统来说是必要的。
一个信号和槽相关的文档说:
All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration. They must also derive (directly or indirectly) from QObject.
所有包含了信号和槽的类必须在它声明的最前面包含Q_OBJECT。它们必须派生(直接或间接)自QObject。
注意,当我们连接信号和槽是实际上是在QObject作用域下完成的:
QObject::connect(sender, signal, receiver, slot);
总是需要Q_OBJECT宏吗?
- 简单的答案是: 否。
- 更好一点的答案是:最好还是带上它。
事实上,Q_OBJECT宏只是在使用信号和槽机制、运行时类型信息、动态属性系统以及为国际化而使用翻译特性时才被需要。
总的来说,不管是否有没有用到以上提到的特性,似乎所有的Qt开发这都强烈建议在每个QObject的子类中使用Q_OBJECT宏。