如何正确清理QWidget/管理一组窗口
How to properly clean-up a QWidget / manage a set of windows?
假设我的应用程序中有 2 个窗口,有两个类负责它们: class MainWindow: public QMainWindow
和class SomeDialog: public QWidget
.
在我的主窗口中,我有一个按钮。单击它时,我需要显示第二个窗口。我是这样做的:
SomeDialog * dlg = new SomeDialog();
dlg.show();
现在,用户在窗口中执行某些操作,并将其关闭。此时,我想从该窗口中获取一些数据,然后,我想,我将不得不delete dlg
.但是,我如何捕捉该窗口关闭的事件?
还是有没有另一种方法可以避免内存泄漏?也许最好在启动时为每个窗口创建一个实例,然后Show()
/Hide()
它们?
我该如何处理此类案例?
建议使用 show()
/exec()
和 hide()
而不是每次要显示对话框时都动态创建对话框。也使用 QDialog
而不是 QWidget
。
在主窗口的构造函数中创建并隐藏它
MainWindow::MainWindow()
{
// myDialog is class member. No need to delete it in the destructor
// since Qt will handle its deletion when its parent (MainWindow)
// gets destroyed.
myDialog = new SomeDialog(this);
myDialog->hide();
// connect the accepted signal with a slot that will update values in main window
// when the user presses the Ok button of the dialog
connect (myDialog, SIGNAL(accepted()), this, SLOT(myDialogAccepted()));
// remaining constructor code
}
在连接到按钮clicked()
事件的插槽中,只需显示它,并在必要时将一些数据传递给对话框
void myClickedSlot()
{
myDialog->setData(data);
myDialog->show();
}
void myDialogAccepted()
{
// Get values from the dialog when it closes
}
从QWidget
和重新实现的子类
virtual void QWidget::closeEvent ( QCloseEvent * event )
http://doc.qt.io/qt-4.8/qwidget.html#closeEvent
此外,看起来您要显示的小部件是一个对话框。因此,请考虑使用 QDialog
或其子类。 QDialog
有有用的信号,你可以连接到:
void accepted ()
void finished ( int result )
void rejected ()
我想你正在寻找Qt::WA_DeleteOnClose窗口标志:http://doc.qt.io/archives/qt-4.7/qt.html#WidgetAttribute-enum
QDialog *dialog = new QDialog(parent);
dialog->setAttribute(Qt::WA_DeleteOnClose)
// set content, do whatever...
dialog->open();
// safely forget about it, it will be destroyed either when parent is gone or when the user closes it.
- 在 c++ 中拥有一组结构的正确方法是什么?
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 一组值的零开销下标运算符
- 使用一组结构,避免在一组结构中出现重复的结构
- CMake:我们可以为一组不形成可执行文件或库的特定文件指定包含目录吗?
- 合并一组模板专用化
- 如何更好地检查两个 char 变量是否在一组值中?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 给定一个枢轴点,按照它们与枢轴点构成的角度递增顺序对一组点进行排序
- 如何从一组变量中查找最低值
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何通过查找迭代器结果分配给一组对的元素
- 读取一组用户输入,按升序排序,然后打印结果
- 如何从一组具有从左到右优先级的整数值创建有序整数键?
- 在 c++ 中定义一组 set 的迭代器
- 使用 C++20 概念强制类实现一组方法
- 这是定义一组递归规则的正确方法吗?
- C++ 将一组对象传递给抽象类的成员函数
- 如何正确清理QWidget/管理一组窗口