[英]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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.