[PyQt] Getting rid of an object

Giovanni Bajo rasky at develer.com
Sun Jun 8 10:55:23 BST 2008

On Sat, 2008-06-07 at 19:01 +0200, David Klasinc wrote:
> Greetings,
> I am facing a rather annoying problem since I have no idea how to get 
> rid of a dialog that I created.
> For example, in an instance of QMainWindow I opened another dialog with
>   self.dialogNew = newDialog (self)
>   self.dialogNew.show ()
> newDialog is a subclassed QDialog with UI created in Qt Designer.
> Now, how do I get rid of that dialog and when will its destructor get 
> called?

Just like C++, newDialog is becoming a child of "self", so it will be
destroyed when you:

   * Destroy "self", or:
   * Delete newDialog

> I implemented __del__ method just too see when it gets called, but it 
> turns out that I can execute
> del self.dialogNew
> and still nothing happens.

"del" is not a substitute of "delete" in C++, because it just drops a
Python reference. If the object has been declared as child of another
object, even if it goes to zero Python reference, it does not get
collected. Otherwise, your code would be a mess (you would always need
to keep references of *anything* around).

If you want to destroy an object, you need to call the C++ "delete" on
it. It's spelled "sip.delete()" in Python. Or you can use .deleteLater()
(a QObject method) for deferred deletion.
Giovanni Bajo
Develer S.r.l.

More information about the PyQt mailing list