Why doesn't calling quit () before exec () exit the application?

Why does this program work fine and display the main window? I expect it to exit, since quit() is called in the constructor.

main.cpp:

 #include<QApplication> #include"MainWindow.h" int main(int argc, char* argv[]) { QApplication app(argc, argv); MainWindow mainWindow; mainWindow.show(); return app.exec(); } 

mainwindow.cpp:

 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { qApp->quit(); } void MainWindow::closeEvent(QCloseEvent *) { qDebug("Hello world!"); } 
+6
source share
2 answers

A call to QCoreApplication::quit() same as a call to QCoreApplication::exit(0) .

If you look at the docs of the last function:

After calling this function, the application leaves the main event loop and returns a call from exec (). The exec () function returns returnCode. If the event loop is not running, this function does nothing .

In your example, the event loop is not already running when the MainWindow constructor is called, so calling quit() does nothing.

+7
source

Since QCoreApplication::quit() does not work until the event loop is started, you need to defer the call until it starts. So the request queue is a deferred method on quit() .

The following lines are functionally identical , or one will work:

 QTimer::singleShot(0, qApp, &QCoreApplication::quit); //or QTimer::singleShot(0, qApp, SLOT(quit())); // or - see https://stackoverflow.com/a/21653558/1329652 postToThread([]{ QCoreApplication::quit(); }); // or QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection); 
+6
source

Source: https://habr.com/ru/post/912726/


All Articles