Search code examples
c++qtuser-interfaceqwidgetwindow-management

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


Let's say I have 2 windows in my application, and two classes responsible for them: class MainWindow: public QMainWindow and class SomeDialog: public QWidget.

In my Main Window I have a button. When it is clicked, I need to display the second window. I do it this way:

SomeDialog * dlg = new SomeDialog();
dlg.show();

Now, the user does something in the window, and closes it. At this point I want to get some data from that window, and then, I suppose, I will have to delete dlg. But how do I catch the event of that window being closed?

Or is there another way not to have a memory leak? Maybe It would be better to create an instance of each window on startup, and then just Show()/Hide() them?

How do I manage such a case?


Solution

  • I think you are looking for the Qt::WA_DeleteOnClose window flag: 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.