5

From what I understand to make dialog Modeless you have to allocate it on the heap. By Doing something like this:

MyDialog* dlg = new MyDialog(this);
dlg->show();
dlg->raise();

Since exec() ignores Modal Property. However now there is a memory leak since nothing deallocates memory pointed to by dlg pointer until the application is closed. I found one solution here http://tinf2.vub.ac.be/~dvermeir/manuals/KDE20Development-html/ch08lev1sec3.html#ch08list09 at the end of the page and was wondering whether there was a less cumbersome way having Modeless dialog.

3 Answers 3

5

You can use the attribute Qt::WA_DeleteOnClose to destroy the window when it is closed/hidden, and QWeakPointer (or QPointer) with a static variable to track the existence of the window inside the slot/function which opens it:

void MyWindow::openDialog() {    
    static QWeakPointer<MyDialog> dlg_;
    if (!dlg_)
        dlg_ = new MyDialog(this);

    MyDialog *dlg = dlg_.data();
    dlg->setAttribute(Qt::WA_DeleteOnClose);
    dlg->show();
    dlg->raise();
    dlg->activateWindow();
}
2

I'd schedule it for deletion at the time it's work is finished by using deleteLater:

void MyDialog::MyDialog(QWidget *parent) {
    // ...
    connect(this, SIGNAL(finished(int)), SLOT(deleteLater)));
}

This approach will preclude you from examining it after the finished signal has been emitted (unless you can guarantee that any accesses happen before everything gets back to the event loop when the deletion is actually performed).

2
  • Thank you. This approach works the only downside That it will require some additional check added to MyDialog to keep it from trying to use delete when it is allocated on the stack or to be never used on the stack when this method is used. Commented Aug 15, 2011 at 20:30
  • I misunderstood your answer thinking that deleteLater is written by the user and not a predefined slot. Now it makes alot more sense and there is no problems with allocation on the stack Commented Aug 17, 2011 at 22:28
2

Personally, I would choose between either using

dlg->setAttribute(Qt::WA_DeleteOnClose);

or making the dialog a -dynamically allocated- member i.e. creating it only once:

// constructor
  : dialog_(0)

// member function
{
  if (! dialog_)
    dialog_ = new MyDialog(this);

  dialog_->show();
  dialog_->raise();
}

This way the dialog is deleted when the parent dies, and only needs to be constructed once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.