Michel Feinstein
Michel Feinstein

Reputation: 14304

Qt UI Closing order

I have a QMainWindow in my project as the center of the GUI and this window can open a new one. I wanted that when the user closes the main window, all the other ones opened by the mais window will close as well.

I tried to place a signal inside the main window's destructor to call the other window close() slot but it doesn't work. I could only make this work by making a closeEvent() in the main window that will send a signal to the other window close slot.

So my question is, how does Qt handles all of this? If the windows exists, why they cant receive a signal if the main window fires it in it's destructor? I fire other signals in the destructor to other threads and they receive them just fine.

Upvotes: 2

Views: 1802

Answers (3)

Your bug is very simple: the destructor is not invoked at the moment that the window is closed. You have already found out that emitting the signal in closeEvent is a solution, so I don't quite see what the problem is.

If you insist on emitting the signal in the destructor, you must do two things:

  1. Allocate the widget on the heap.

  2. Set the Qt::WA_DeleteOnClose attribute on the widget.

int main() {
  QScopedPointer<MyWidget> widget(new MyWidget);
  widget->setAttribute(Qt::WA_DeleteOnClose);
  ...
}

Upvotes: 0

vahancho
vahancho

Reputation: 21258

I would do this in the following way:

void MyMainWindow::closeEvent(QCloseEvent *e)
{
    foreach (QWidget *widget, QApplication::topLevelWidgets()) {
        if (widget != this) { // avoid recursion.
            widget->close();
        }
    }
    e->accept();
}

The code above will search and close all top level windows as soon as the main window is closing.

Upvotes: 1

Metoo
Metoo

Reputation: 400

There are two ways of solving this and both ways are working for me :

METHOD 1: if you want to delete them when closed, then set the attribute Qt::WA_DeleteOnClose. The children are automatically deleted when the parent is deleted.

For your QMainWindow instance call setAttribute(Qt::WA_DeleteOnClose) method Ex: My main.cpp

    #include "st.h"
    #include <QtGui/QApplication>

    int main(int argc, char *argv[])
    {
  QApplication a(argc, argv);
  St *w = new St();
  w->setAttribute(Qt::WA_DeleteOnClose);
  w->show();
  return a.exec();
    }

Also pass the "this" pointer to whatever child windows you are creating. But then you have create the QMainWindow instance on the heap and not on the stack otherwise your application will crash.

METHOD 2:

Overload the closeEvent method for your QMainWindow and in that close event method ,call deleteLater() method for all the childs.

     void St::closeEvent(QCloseEvent *c)
     {
   m_b->deleteLater();//This is a pushbutton
   odlg->deleteLater();//This is child dialog
       //both are children of QMainWindow

     }

Upvotes: 0

Related Questions