I have a layout that I add a lot of custom widgets to with something like layout.addWidget(widget)
. Later I want to remove all those custom widgets and add new ones. I'm confused on the best way to do this when it comes to deleteLater
and setParent(None)
. For example, here's my cleanup function that's called for all the widgets in the layout:
def _removeFilterWidgetFromLayout(self, widget):
"""Remove filter widget"""
self._collection_layout.removeWidget(widget)
widget.setParent(None)
widget.deleteLater()
I have a suspicion that not all of these lines are needed to properly cleanup the memory used by the widget. I'm unsure of what is happening with the C++ and Python references to widget
.
Here's what I understand about the C++ and Python references to QObjects in PyQt.
I believe that when you add a widget to a layout the widget becomes a child of the layout. So, if I call removeWidget
then the parent relationship is broken so I have to clean up the C++ and Python reference myself since the widget has no other parent. The call to setParent
is an explicit way of removing the parent relationship with the layout. The call to deleteLater
is meant to take care of the C++ reference.
The Python reference is garbage collected because the widget
variable goes out of scope, and there are no other Python objects pointing to widget
.
Do I need to call setParent
and deleteLater
or would deleteLater
be enough to properly clean this up?
As a side note, I've found that calling setParent(None)
is a very expensive function call in this scenario. I can greatly speed up my entire cleanup process by removing this call. I'm not sure if deleteLater
is enough to clean everything up correctly. Here's my profiling output from line_profiler
:
Line # Hits Time Per Hit % Time Line Contents
==============================================================
2167 @profile
2168 def _removeFilterWidgetFromLayout(self, widget):
2169 """Remove filter widget"""
2170
2171 233 1528 6.6 1.0 self._collection_layout.removeWidget(widget)
2172 233 143998 618.0 97.9 widget.setParent(None)
2173 233 1307 5.6 0.9 widget.deleteLater()
When using PyQt4 is there an 'accepted' way to do this cleanup? Should I use setParent
, deleteLater
, or both?