nathanesau
nathanesau

Reputation: 1721

Qt - How to handle memory management for dialogs?

I am running into the following issue:

The result is that dlg never gets deleted (it will only get deleted once centralWidget() gets deleted).

The call stack is something like this:

MainWindow::newAction ()
...
MainWindow::newAction()

I am wondering how to handle this case. I want all of the local dialog variables from the first call to newAction() to be deleted by the time we go into the function newAction() again.

Upvotes: 0

Views: 341

Answers (2)

andrey.s
andrey.s

Reputation: 849

You also can try something like this:

void MainWindow::newAction() {

    const auto dialog = new MyDialog(centralWidget());

    // When user will close the dialog it will clear itself from memory
    connect(dialog, &QDialog::finished, [dialog]() {
        dialog->deleteLater();
    });

    dialog->exec();
}

However, a good move would be to stop user from summoning more QDialogs than a single one, given that this one is a modal dialog(might be a good idea to keep this dialog pointer as a class member and check is it on screen already before calling exec() on it.

Upvotes: 2

aalli mahmood
aalli mahmood

Reputation: 21

If i understood the question right, you want one dialog to be opened and want to delete it before a new dialog request comes in?

If that's the case you can do following:

In MainWindow.h declare QDialog *dlg = nullptr

In your MainWindow.cpp newAction() function you can do following:

void newAction()
{
   if(dlg != nullptr)
   {
    dlg->close();
    dlg->deleteLater();
    //or
    //dlg->destroy(); // this will immediately free memory
   }
   dlg = new QDialog(centralWidget());
   ...
   //dlg->exec(); // This will automatically make QDialog modal.
   dlg->show(); // This will not make a QDialog modal. 
}

I hope this will help. Remember QDialogs when displayed with exec() they automatically behave as Modal window. show() will make it non-modal.

Upvotes: 1

Related Questions