Qt-如何处理对话框的内存管理?

时间:2019-05-09 22:15:48

标签: c++ qt memory

我遇到了以下问题:

  • 用户按下“ Ctrl + N”键进入功能MainWindow :: newAction()
  • 在MainWindow :: newAction()中,创建一个QDialog dlg(centralWidget())并调用dlg.exec()
  • 打开dlg时,用户再次按下“ Ctrl + N”

结果是dlg永远不会被删除(仅在centralWidget()被删除后才会被删除)。

调用堆栈是这样的:

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

我想知道如何处理此案。我希望在我们再次进入函数newAction()时,删除从第一次调用newAction()以来的所有局部对话框变量。

2 个答案:

答案 0 :(得分:2)

您也可以尝试以下操作:

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();
}

但是,一个好的方法是阻止用户召集更多的QDialogs,因为这是一个模态对话框(将这个对话框指针保持为类成员并检查它是否已经在屏幕上可能是一个好主意。在调用exec()之前。

答案 1 :(得分:1)

如果我理解正确的问题,您希望打开一个对话框并想在新对话框请求出现之前将其删除吗?

在这种情况下,您可以执行以下操作:

MainWindow.h中声明QDialog *dlg = nullptr

在您的MainWindow.cpp newAction()函数中,您可以执行以下操作:

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. 
}

我希望这会有所帮助。请记住,QDialog与exec()一起显示时,它们会自动充当模态窗口。 show()将使其变为非模态。