[PyQt] Deleting a PyQt object

Phil Thompson phil at riverbankcomputing.co.uk
Thu Nov 22 10:02:22 GMT 2007


On Thursday 22 November 2007, Fabian Steiner wrote:
> Hello!
>
> I'm currently working on a programm which adds a QTableWidget to an
> existing QGridLayout using QGridLayout.addWidget(). When the user pushes
> button btn1, this QTableWidget should disappear and the layout should free
> the space.
>
> In order to achieve this aim I tried the following:
>
> [...]
> self.ui.gridlayout.removeWidget(self.legend)
> del self.legend
> [...]
>
> => The QTableWidget is indeed removed from the layout, but still exists in
> the GUI.
>
> [...]
> self.ui.gridlayout.removeWidget(self.legend)
> import sip
> sip.delete(self.legend)
> [...]
>
> => works as expected
>
> Is this really the right way to do it?

I prefer...

self.legend.setParent(None)

...or...

self.legend.deleteLater()

> Why doesn't the del-approach work? 
> Actually no other PyQT objects should hold any other references to
> self.legend.

When a QObject has a parent it is owned by that parent. When the C++ object is 
owned an extra reference is kept to the Python object under the covers. This 
is needed in case the object is either a Python sub-class or you have stashed 
extra attributes in the instance dictionary.

Therefore you need to either call the C++ dtor (using sip.delete()), arrange 
for it to be called (using deleteLater()), or change the ownership back to 
Python (using setParent()). Changing the ownership also removes that extra 
reference so that the object is available to be garbage collected when it 
goes out of scope.

Phil


More information about the PyQt mailing list