简体   繁体   English

QObject派生类型需要父QObject吗?

[英]Do QObject derived types need a parent QObject?

I am writing some Qt class which is derived from QObject , it looks like: 我正在编写一些从QObject派生的Qt类,它看起来像:

class A : public QObject
{
    Q_OBJECT
public: A() : QObject() {}
.....
}

but in several places I saw, that the QObject derived classes all have a parent, like: 但在我看到的几个地方,QObject派生类都有一个父类,如:

class A : public QObject
{
    Q_OBJECT
public: A(QObject* parent = 0) : QObject(parent) {}
.....
}

So the question is: do I need a parent or not? 所以问题是:我是否需要父母? What is the difference if I have one, if I have a default one (0) or I don't have at all? 如果我有一个,如果我有一个默认的(0)或者根本没有,那有什么区别?

As such you don't need a parent. 因此,您不需要父母。

But setting parent has some advantage in terms of garbage collection. 但设置父级在垃圾收集方面具有一些优势。

If you set a parent then when parent gets deleted, it will also delete all its children. 如果您设置了父项,那么当父项被删除时,它也将删除其所有子项。

Following excerpt from the doc : 以下摘自文档

QObjects organize themselves in object trees. QObjects在对象树中组织自己。 When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. 当您使用另一个对象作为父对象创建QObject时,该对象将自动将其自身添加到父对象的children()列表中。 The parent takes ownership of the object; 父母取得对象的所有权; ie, it will automatically delete its children in its destructor. 即,它将自动删除其析构函数中的子项。 You can look for an object by name and optionally type using findChild() or findChildren(). 您可以按名称查找对象,也可以使用findChild()或findChildren()键入。

You should allow setting a parent 您应该允许设置父级
if you want to allow moving some object containing a member of type class A to another thread. 如果要允许将包含class A成员的对象移动到另一个线程。
(Which you're not really able to prevent.) (你真的无法阻止。)
In this case, the member A probably has to be moved, too. 在这种情况下,成员A也可能必须移动。

From the docs : 来自文档

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. 在更改线程关联之前,将QEvent :: ThreadChange事件发送到此对象。 You can handle this event to perform any special processing. 您可以处理此事件以执行任何特殊处理。 Note that any new events that are posted to this object will be handled in the targetThread. 请注意,发布到此对象的任何新事件都将在targetThread中处理。

So if you don't allow passing a parent, the maintainer of the object containing your class would have to override event() , check for QEvent::ThreadChange and move A manually. 因此,如果您不允许传递父对象,则包含您的类的对象的维护者必须覆盖event() ,检查QEvent::ThreadChange并手动移动A.

From the docs : 来自文档

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. 在更改线程关联之前,将QEvent :: ThreadChange事件发送到此对象。 You can handle this event to perform any special processing. 您可以处理此事件以执行任何特殊处理。 Note that any new events that are posted to this object will be handled in the targetThread. 请注意,发布到此对象的任何新事件都将在targetThread中处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM