[PyQt] memory management

Maurizio Berti maurizio.berti at gmail.com
Mon Aug 27 23:54:19 BST 2018

Python automatically takes care of memory using its garbage collector,
meaning that it (should) delete an object when it thinks that that object
is not needed anymore. This is really convenient, as you don't usually need
to care about deleting [Q]Objects unless you really have a good reason to
do that.

PyQt is a wrapper, and things can get messy sometimes.
This means that there are situations in which an object might still exist
as a Python wrapped object while its C++ counterparts don't. Also, Python
"needs" a QObject [sub]class to be properly initialized only to use
QObject's Qt C++ wrapped methods, so a QObject Python class might exist
even if its C++ object doesn't.

Anyways, usually you give a parent to an object when you really need it to
have a parent (for example, because you need to easily access it using
parent()), unless Qt takes care of it, like when adding widgets to layouts;
otherwise, it's enough to set it as another object's attribute or property,
including basic objects like lists or dictionaries: if you delete that
"main" object and it's QObjects attributes are not parented with or used by
another object, they will be deleted along with it.
This obviously means that a QObject deleted using deleteLater() might still
exist as a Python object, for example, because it's stored in a list
somewhere else.
Theoretically this also means that the memory used by the wrapped QObject
should be freed after deleteLater(), leaving only the Python object in
memory (until the object is actually deleted with del).

An interesting article about this:

PS: I'm not an expert in low-level programming and memory management,
please correct me if I wrote anything wrong.

2018-08-27 21:27 GMT+02:00 Christopher Probst <christop.probst at gmail.com>:

> Hello,
> I am from the C++ world. Is there still a reason to provide a parent to a
> QObject in pyQt to ensure that children are deleted when a QObject is
> deleted?
> Thanks,
> Christopher
> _______________________________________________
> PyQt mailing list    PyQt at riverbankcomputing.com
> https://www.riverbankcomputing.com/mailman/listinfo/pyqt

È difficile avere una convinzione precisa quando si parla delle ragioni del
cuore. - "Sostiene Pereira", Antonio Tabucchi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20180828/4fae9bab/attachment.html>

More information about the PyQt mailing list