如何正确清理QWidget/管理一组窗口

How to properly clean-up a QWidget / manage a set of windows?

本文关键字:一组 窗口 管理 何正确 QWidget      更新时间:2023-10-16

假设我的应用程序中有 2 个窗口,有两个类负责它们: class MainWindow: public QMainWindowclass 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.