QT-如何处理对话框的内存管理
Qt - How to handle memory management for dialogs?
我正在遇到以下问题:
- 用户按" 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()
将使它成为非模式。
相关文章:
- 如何在Qbutton的帮助下更改Q对话框的宽度
- 当对话框被接受时,如何用参数调用槽
- WinAPI 在单击第一个对话框上的按钮控件并销毁第一个对话框后创建第二个对话框
- 如何多次询问来自QML对话框的输入?
- 选择文件对话框错误
- 自定义对话框(源自QDialog)不会关闭(Android)
- 如何在 MFC 对话框中使用 OnDraw
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- 从资源视图访问对话框时出现问题
- 如何检测窗口当前是否正在运行模式对话框?
- "最小化"按钮不会出现在 MFC 对话框中
- 如何获取QNetworkConfiguration UserChoice对话框?
- 表单显示对话框函数错误,并且不执行下面的语句
- 如何在 VC6 中的对话框中将图标设置为按钮
- C++/Win32 构造函数不使用从对话框获取的字符串初始化变量
- QT-如何处理对话框的内存管理
- 从C++打开文件对话框时,JNI内存泄漏
- 如何测量对话框所需的内存
- 打开文件对话框和内存泄漏
- 如何释放在子对话框中创建的CWin对象以避免内存泄漏