我应该需要删除还是关闭后?
Should I need delete or after close?
我有一个带有 "Settings" 按钮的表单(继承自 QMainWindow)需要显示设置表单(继承自 QWidget)。
Button click() 连接到一些 settingsButtonClick() 插槽
并在设置按钮点击:
void MainQT::settingsButtonClick()
{
SettingsForm *settingsForm = new settingsForm();
settingsForm->show();
}
它工作正常,但问题是我是否需要在某处删除此表单,或者当我关闭设置表单时它会被删除?
在这种情况下,我管理内存的正确方法是什么?我是否应该在 MainForm 的 ctor 中实例化设置表单并仅在请求时显示?
我会按以下方式进行:
void MainQT::settingsButtonClick()
{
SettingsForm *settingsForm = new settingsForm();
settingsForm->setAttribute( Qt::WA_DeleteOnClose );
settingsForm->show();
}
使用 Qt::WA_DeleteOnClose
将确保 settingsForm
在您关闭后被删除。
有关详细信息,请查看 Qt documentation.
should I delete this form somewhere or it would be deleted when I close settings form? What is the correct way to manage memory in this case? Should I instantiate settings form in MainForm's ctor hidden and only show on request?
对此没有严格的规定,您可以:
- 每次需要显示时创建设置对话框,然后销毁对象;
- 在 MainForm 构造函数中创建设置对话框,然后在用户操作时显示它;
- 您甚至可以使用“设置”对话框作为容器来存储设置值
请注意,您的代码会创建新对象并且永远不会销毁它,这会导致内存泄漏;考虑将指针保存为成员变量并在用户再次打开“设置”对话框时重新使用它:
void MainQT::settingsButtonClick()
{
if(!mSettingsForm) mSettingsForm = new settingsForm();
settingsForm->show();
}
我有一个带有 "Settings" 按钮的表单(继承自 QMainWindow)需要显示设置表单(继承自 QWidget)。
Button click() 连接到一些 settingsButtonClick() 插槽
并在设置按钮点击:
void MainQT::settingsButtonClick()
{
SettingsForm *settingsForm = new settingsForm();
settingsForm->show();
}
它工作正常,但问题是我是否需要在某处删除此表单,或者当我关闭设置表单时它会被删除? 在这种情况下,我管理内存的正确方法是什么?我是否应该在 MainForm 的 ctor 中实例化设置表单并仅在请求时显示?
我会按以下方式进行:
void MainQT::settingsButtonClick()
{
SettingsForm *settingsForm = new settingsForm();
settingsForm->setAttribute( Qt::WA_DeleteOnClose );
settingsForm->show();
}
使用 Qt::WA_DeleteOnClose
将确保 settingsForm
在您关闭后被删除。
有关详细信息,请查看 Qt documentation.
should I delete this form somewhere or it would be deleted when I close settings form? What is the correct way to manage memory in this case? Should I instantiate settings form in MainForm's ctor hidden and only show on request?
对此没有严格的规定,您可以:
- 每次需要显示时创建设置对话框,然后销毁对象;
- 在 MainForm 构造函数中创建设置对话框,然后在用户操作时显示它;
- 您甚至可以使用“设置”对话框作为容器来存储设置值
请注意,您的代码会创建新对象并且永远不会销毁它,这会导致内存泄漏;考虑将指针保存为成员变量并在用户再次打开“设置”对话框时重新使用它:
void MainQT::settingsButtonClick()
{
if(!mSettingsForm) mSettingsForm = new settingsForm();
settingsForm->show();
}