什么时候应该使用Q_OBJECT? [英] When should Q_OBJECT be used?

查看:857
本文介绍了什么时候应该使用Q_OBJECT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档说明:


Q_OBJECT宏必须出现在类定义的
private节中
,它声明自己的信号和
槽或使用Qt的元对象系统提供的其他服务


确切是什么意思?在哪些QObject派生类可以安全地忽略它?如果您在QObject派生类上省略Q_OBJECT,然后继承那个问题,会出现问题吗?基本上我想更多的信息,当我可以省略它从我的Qt类。

解决方案

对于从 QObject 派生的任何非模板化类, c $ c> Q_OBJECT
$ b

除了信号和槽之外, Q_OBJECT 宏提供与给定类相关联的元对象信息。 / p>

文档中所述:


我们强烈建议 QObject的所有子类使用Q_OBJECT宏,无论它们是否实际使用信号, ,和属性。


假设我们有以下类:

  class Class:public QObject {
public:
Class(){}
};

没有 Q_OBJECT (其他)不适用于 Class


  1. qobject_cast< Class>() - 由于缺少元数据


  2. QObject :: tr ( $ <$> $ <$> $ <$>

  3. c>,当通过名称调用或查找时, QMetaObject 方法不会用于这些方法,Qt 4 也不会连接 - 由于缺少元数据


  4. 信号 - 由于 moc


当然,你可以忽略它,但如果你使用这些功能,你需要记住把宏放到类的声明中。这是一个相当脆弱的做法,最好避免。节省是不值得的。因此,不要等待 - 将 Q_OBJECT 宏添加到源自 QObject 的每个类作为编码策略。



Q_OBJECT 宏应该永远不会用于不导出的类从 QObject 。要向这些类添加调用和属性,请改用 Q_GADGET 宏。


The documentation states that:

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.

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.

解决方案

You should use the Q_OBJECT macro for any non-templated classes that derive from QObject.

Besides signals and slots, the Q_OBJECT macro provides the meta object information that is associated with given class.

As stated in the documentation:

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.

Suppose we have the following class:

class Class : public QObject {
public:
  Class() {}
};

Without Q_OBJECT, the following metaobject system features (among others) will not work for Class:

  1. qobject_cast<Class>() - due to missing metadata

  2. QObject::tr() - due to missing metadata

  3. 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

  4. signals - since moc won't generate their implementations and the code won't compile.

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.

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.

这篇关于什么时候应该使用Q_OBJECT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆