Do QObject derived types need a parent QObject?

情到浓时终转凉″ 提交于 2019-12-05 09:31:24
Kunal

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().

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.

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