[PyKDE] Destroying pyqt child widgets

Brent Burley Brent.Burley at disney.com
Fri Nov 16 21:28:24 GMT 2001


Boudewijn Rempt wrote:
> What I do if I really want to delete a widget (one that doesn't
> react correctly to the WM_Destructive_Close or whatever it's called
> hint, so close() doesn't destroy it), is w.parent.removeChild(w).

Thanks.  removeChild does seem to do the trick in most cases and
certainly seems like the cleaner approach.  However, it relies on the
Python references going away before the widget can be destroyed.  This
is usually fine unless you have a reference leak (which still seems to
happen a lot in PyQt unfortunately).  If you do have a reference leak,
removeChild will leave you with a child widget that is still being
displayed but is now unmanaged - a bad situation.

The w.reparent(QWidget(), 0, QPoint()) method should always destroy the
widget immediately and then at least on the Qt side you won't have a
leak.

Here's a simple testbed to see what can happen:

from qt import *

class MyLabel(QLabel):
    def __del__(self):
	print 'del MyLabel'

class MyUI(QVBox):
    def __init__(self, parent=None):
	QVBox.__init__(self, parent)
	self.label1 = MyLabel("label1", self)
	self.label2 = MyLabel("label2", self)
	self.label3 = MyLabel("label3", self)
	self.button = QPushButton("delete label2", self)
	self.connect(self.button, SIGNAL("clicked()"), self.deleteLabel2)
    def deleteLabel2(self):
	print 'trying to delete label2'
	self.removeChild(self.label2)
	# self.reparent(QWidget(), 0, QPoint())
	# del self.label2

import sys
app = QApplication(sys.argv)
ui = MyUI()
ui.show()
app.exec_loop()




More information about the PyQt mailing list