問題描述
文檔指出:
Q_OBJECT 宏必須出現(xiàn)在類定義的私有部分聲明自己的信號和插槽或使用其他服務(wù)由 Qt 的元對象系統(tǒng)提供.
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.
但是正是這是什么意思?在哪些 QObject 派生類上我可以安全地省略它?如果在 QObject 派生類上省略 Q_OBJECT,然后從該類繼承,會出現(xiàn)問題嗎?基本上,我想了解更多有關(guān)何時可以從 Qt 類中省略它的信息.
But exactly what does that mean? On which QObject-derived classes can I safely omit it? Will problems arise if you omit Q_OBJECT on a QObject-derived class, and then inherit from that one? Basically I would like a little more information on when I can omit it from my Qt classes.
推薦答案
對于從 QObject
派生的任何非模板類,您應(yīng)該使用 Q_OBJECT
宏.
You should use the Q_OBJECT
macro for any non-templated classes that derive from QObject
.
除了信號和槽之外,Q_OBJECT
宏提供了與給定類相關(guān)聯(lián)的元對象信息.
Besides signals and slots, the Q_OBJECT
macro provides the meta object information that is associated with given class.
如文檔中所述:
我們強烈建議QObject 的所有子類都使用 Q_OBJECT 宏,無論它們是否實際使用信號、槽和屬性.
we strongly recommend that all subclasses of QObject use the Q_OBJECT macro regardless of whether or not they actually use signals, slots, and properties.
假設(shè)我們有以下類:
class Class : public QObject {
public:
Class() {}
};
如果沒有 Q_OBJECT
,以下元對象系統(tǒng)功能(以及其他)將不適用于 Class
:
Without Q_OBJECT
, the following metaobject system features (among others) will not work for Class
:
qobject_cast
- 由于缺少元數(shù)據(jù)()
QObject::tr()
- 由于缺少元數(shù)據(jù)
slots 和 invokables 首先在 Class
中聲明,當(dāng)按名稱調(diào)用或查找時 - QMetaObject
方法都不適用于這些方法,Qt 也不會4 connect
- 由于缺少元數(shù)據(jù)
slots and invokables first declared in Class
, when invoked or looked up by name - none of QMetaObject
methods will work for these methods, neither will the Qt 4 connect
- due to missing metadata
信號 - 因為 moc
不會生成它們的實現(xiàn),代碼也不會編譯.
signals - since moc
won't generate their implementations and the code won't compile.
當(dāng)然,您可以省略它,但是如果您曾經(jīng)使用過這些功能,則需要記住將宏放入類的聲明中.這是一種相當(dāng)脆弱的做法,最好避免.節(jié)省的錢不值得.所以,不要等待 - 將 Q_OBJECT
宏添加到從 QObject
派生的每個類中,作為編碼策略的問題.
You can omit it, of course, but if you ever use these features, you'll need to remember to put the macro into the class's declaration. This is a rather brittle practice and best avoided. The savings are not worth it. So, don't wait - add the Q_OBJECT
macro to every class that derives from QObject
as a matter of coding policy.
Q_OBJECT
宏應(yīng)該永遠(yuǎn)用在不是從 QObject
派生的類上.要將可調(diào)用項和屬性添加到此類類,請改用 Q_GADGET
宏.
The Q_OBJECT
macro should never be used on classes that don't derive from QObject
. To add invokables and properties to such classes, use the Q_GADGET
macro instead.
這篇關(guān)于什么時候應(yīng)該使用 Q_OBJECT?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!