Search code examples
c++qtpointersdelete-operator

Delete memory to window handle from child on close in QT


Let see my conf:

mainwindow.h
second_window.h
  1. Keep pointer to second_window in class methods ( public: second_window * h_window; )
  2. Class mainwindow opens second_window.

In second_window i catch eventClose(); And there i want to delete h_window; But i got a access error, i thought that window is still opened so when i try to delete pointer memory i got error.

Other idea when i should delete this pointer?


Solution

  • If both windows are independant and thus having no parents, then a way to solve is with QPointer and setAttribute(Qt::WA_DeleteOnClose).

    class mainwindow : public QWidget {
      public:
        ~mainwindow() {
          delete h_window; // deletes h_window if it is not 0 (that is, not closed yet)
        }
        void showSecondWindow() {
          if ( ! h_window ) {
            h_window = new second_window();
          }
          h_window->show();
          h_window->activateWindow();
        }
      private:
        QPointer<second_window> h_window; // h_window will automatically become 0 when second_window is deleted.
    }
    
    class second_window : public QWidget {
      public:
        second_window() {
          setAttribute(Qt::WA_DeleteOnClose); // automatically delete itself when window is closed
        }
    }