[PyKDE] Issue with QDialog and lifetime

John Ridley ojokimu at yahoo.co.uk
Wed May 25 20:19:06 BST 2005


--- Giovanni Bajo <rasky at develer.com> wrote:
> 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.

If there are lots of dialogs in an app, I would use a simple
DialogManager class which wrapped the create/exec/close for the modal
dialogs. This would at least save me having to remember to clean up all
the time. But I'm sure you must be doing something like this yourself
already.

To work around the specific problems with Qt.WDestructiveClose, I have
always used the "alsoDelete" overload of QWidget's close method.
However, AFAIK, there is no guarantee that this will always kill the
widget. The function does return a boolean indicating success/failure
though, so I suppose something fairly robust could be developed around
it.

HTH


John Ridley


		
___________________________________________________________ 
How much free photo storage do you get? Store your holiday 
snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com




More information about the PyQt mailing list