Python/PyQt freeing of objects
-
I have inherited a large body of Python/PyQt code. I note the following:
- Some
QDialog
s haveQtCore.Qt.WA_DeleteOnClose
set, while some don't. - Some
QWidget
/QBoxLayout
s are created viaQWidget(self)
(whereself
is theQDialog
), while some (most) are created via plainQWidget()
.
Bear in mind that all Python/PyQt objects are created on the heap not the stack (i.e. C++
QWidget* w = new QWidget()
notQWidget w
). I am aware that in ("unmanaged") C++ it is the caller's responsibility todelete
suchnew
ed 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.
- Some
-
Hi,
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. -
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).