Qt QObject QObject Lifetime and Ownership

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

QObjects come with their own alternative lifetime concept compared to native C++'s raw,unique or shared pointers.

QObjects have the possibility to build an objecttree by declaring parent/child relationships.

The simplest way to declare this relationship is by passing the parent object in the constructor. As an lternative you can manually set the parent of a QObject by calling setParent. This is the only direction to declare this relationship. You cannot add a child to a parents class but only the other way round.

QObject parent;
QObject child* = new QObject(&parent);

When parent now gets deleted in stack-unwind child will also be deleted.

When we delete a QObject it will "unregister" itself form the parent object;

QObject parent;
QObject child* = new QObject(&parent);
delete child; //this causes no problem.

The same applies for stack variables:

QObject parent;
QObject child(&parent);

child will get deleted before parent during stack-unwind and unregister itself from it's parent.

Note: You can manually call setParent with a reverse order of declaration which will break the automatic destruction.



Got any Qt Question?