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

Qt - How to handle memory management for dialogs?

本文关键字:对话框 内存 管理 处理 何处理 QT-      更新时间:2023-10-16

我正在遇到以下问题:

  • 用户按" ctrl n",将进入函数mainwindow :: newaction((
  • 在MainWindow :: NewAction((中,创建一个QDialog DLG(CentralWidget(((,并调用DLG.EXEC((
  • 当DLG打开时,用户再次按下" Ctrl N"

结果是DLG永远不会被删除(只有删除CentralWidget((才会被删除(。

呼叫堆栈是这样的:

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

我想知道如何处理这种情况。我希望从第一个呼叫到newAction((的所有本地对话框变量都会在我们再次进入函数newAction((时删除。

您也可以尝试这样的东西:

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

但是,一个好的举动是阻止用户召唤更多的qdialog,而不是单个qdialog,鉴于此是一个模态对话框(可能是将此对话框指针作为班级成员的一个好主意,并且检查是否在屏幕已经在它上调用 exec()之前。

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

如果是这种情况,您可以按以下操作:

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

我希望这会有所帮助。请记住QDialogs使用exec()显示时,它们会自动以模态窗口行为。show()将使它成为非模式。