[PyKDE] Issue with QDialog and lifetime

Giovanni Bajo rasky at develer.com
Wed May 25 16:13:28 BST 2005


Hello,

while the QObject object model is pretty clear to me, and I also understand
the way it was translated to Python, today I stumbled upon an issue which I
hadn't realized before:

class MyMainWindow(QMainWindow):
    def about(self):
         dlg = MyAboutDlg(self)
         dlg.exec_loop()

This way of using modal dialog is not safe because the dialog is not
deallocated after usage! In fact, its lifetime is bound to that of the main
window. In fact, the code above is equivalent to:

void MyMainWindow::about(void)
{
    MyAboutDlg* dlg = new MyAboutDlg(this);
    dlg->exec();
}

Instead, the idiomatic way of using modal dialogs in C++ is:

void MyMainWindow::about(void)
{
    MyAboutDlg dlg(this);
    dlg.exec();
}

which has not direct translation in Python.

I would like to stress that this is not a general complaint against the way
PyQt handles lifetime issues (which is kind of perfect, IMO), but a nasty
side-effect which happens only for modal dialogs because of the way they are
idiomatically used (allocated on the stack to be automatically destroyed
when the calling function exits).

So, I don't see any easy way to take care of this automatically. One has to
remember to manually destroy the dialog calling deleteLater (which kind of
sucks because it means that we are back to manually memory management for
dialogs), or creating the dialog with Qt.WDestructiveClose (but then it is
impossible to access the result() of the dialog after exec_loop() exits).

Suggestions? I guess this issue should be highlighted in the documentation.
-- 
Giovanni Bajo




More information about the PyQt mailing list