Solved Properly quitting an application when main window closes
-
If a user closes the main window by clicking the 'x' in the upper right hand window, I understand that this doesn't close the application but rather just hides the main window.
As such, I have added in the constructor of my main window:this->setAttribute( Qt::WA_DeleteOnClose );
But it seems that the codes is entering the destructor of the main window twice. The second time, the application crashes, of course, because this is invalid.
If the user quits through the file menu, the code enters the destructor only once.
What have I done wrong? -
@mgreenish said in Properly quitting an application when main window closes:
If a user closes the main window by clicking the 'x' in the upper right hand window, I understand that this doesn't close the application but rather just hides the main window.
No, the default behaviour is to quit the application, see the docs.
If your application is not quitting after clicking "x", you probably have some code which prevents it from doing so.
-
The main window destructor should run only once. I would suggest you to do not use that attribute if you already delete your mainwindow in the destructor.
Are you using QtCloseEvent? It can prevents your main window from closing.
-
@sierdzio: Actually, now I remember why I got here. I have setQuitOnLastWindowClosed( false ) because there are times on start up where the main window doesn't open right away and the application was closing right away. So I have set it false in the main
a.setQuitOnLastWindowClosed(false);
And then call
this->setAttribute( Qt::WA_DeleteOnClose );
later in the main window class once I know all the windows have opened.
-
The double entry happens only in OS X, not in Windows.
-
Hi,
You should rather determine why you have that behaviour on macOS rather than working around it.
What are you doing when your application starts up ?
-
How do you instanciate the window ?
The following will crash for sure when closing it or quit the app :QWidget w; w.setAttribute(Qt::WA_DeleteOnClose); w.show();
The window must be instanciated dynamically with new.
-
@mpergand That explains that, the window is not instantiated with new.
-
So I was wrong, I double checked and the code enters the destructor twice on Windows as well, crashing the application.
The solution is not to set Qt::WA_DeleteOnClose within the main application window, but rather to override the closeEvent function that is part of the QMainWindow class and call a function that calls QApplication::quit() from there (trying to call QApplication::quit() directly from within closeEvent caused an error).
-
It's not a question of main application window. It has to do with the fact that you are creating a local object on the stack which means that the widget will get closed and destroyed in the method.