[PyQt] Deleting a PyQt object
phil at riverbankcomputing.co.uk
Thu Nov 22 10:02:22 GMT 2007
On Thursday 22 November 2007, Fabian Steiner wrote:
> 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:
> del self.legend
> => The QTableWidget is indeed removed from the layout, but still exists in
> the GUI.
> import sip
> => works as expected
> Is this really the right way to do it?
> Why doesn't the del-approach work?
> Actually no other PyQT objects should hold any other references to
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.
More information about the PyQt