Important: Please read the Qt Code of Conduct -

Python/PyQt freeing of objects

  • I have inherited a large body of Python/PyQt code. I note the following:

    • Some QDialogs have QtCore.Qt.WA_DeleteOnClose set, while some don't.
    • Some QWidget/QBoxLayouts are created via QWidget(self) (where self is the QDialog), while some (most) are created via plain QWidget().

    Bear in mind that all Python/PyQt objects are created on the heap not the stack (i.e. C++ QWidget* w = new QWidget() not QWidget w). I am aware that in ("unmanaged") C++ it is the caller's responsibility to delete such newed objects, else they leak. In Python, however, I understand it to be "managed" (i.e. reference counting), so it will delete referenced objects once they go out of scope (right?).

    So, my question is: is it OK to let Python manage all this and not have to worry about closing or passing a parent, without any leaking? I am not asking about "best practice" here, I need a definitive understanding of current behaviour as there are hundreds of such calls with no seeming consistency.

  • Lifetime Qt Champion


    Widgets put in a layout get reparented to the widget where the layout is set so they don't need the self parameter when created.

    Layouts which get a parent on construction are set on that widget. It saves a call to setLayout(whateverLayout).

  • @SGaist
    Thank you. With all due respect (and you deserve a lot of that!), that was not the question. The question is: when using Python/PyQt, do I ever have to care whether widgets/layouts do or do not get reparented, or can I rely on Python's reference counting & disposal system to do all necessary clean up for me (in a way that does not apply to [unmanaged] C++) ? That's why this question is in the Language Bindings section of the forum.

  • Lifetime Qt Champion

    This stackoverflow answer contains a pretty nice explanation.

    Short version: do care about that properly. There are two counting involved: the one from python and the one from Qt (parent/child relationship).

  • @SGaist
    Great stuff --- I'll study that link.

Log in to reply