Do QObject derived types need a parent QObject?

淺唱寂寞╮ 提交于 2019-12-22 07:52:27

问题


I am writing some Qt class which is derived from QObject, it looks like:

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:

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?


回答1:


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. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() or findChildren().




回答2:


You should allow setting a parent
if you want to allow moving some object containing a member of type class A to another thread.
(Which you're not really able to prevent.)
In this case, the member A probably has to be moved, too.

From the docs:

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. 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.

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.

From the docs:

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. 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.



来源:https://stackoverflow.com/questions/16784896/do-qobject-derived-types-need-a-parent-qobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!