How process remaining events before shutdown
-
My simple(ish) app outputs information using qDebug statements in destructors. I notice that when my app shuts down via exit(0), those qDebug statements don't run - or at least I don't see the output.
Is there a statement I can place as the last line of my main.cpp to perform any remaining outputs, handle any remaining events in the event loop, etc. ?
-
@ocgltd
Basically once you are insideQCoreApplication::exec()
that is when you should always useQCoreApplication::quit()
. This does not actually exit the application, rather it exits thea.exec()
you have. Code then executes anything after that in your call, which is usually nothing, as in yourreturn a.exec();
being the final statement in yourmain()
function.Using
QCoreApplication::quit()
(or more rarelyQCoreApplication::exit()
) exits the Qt application event loop "cleanly", and allows proper clean up. Using the non-Qt systemexit()
directly exits the C++ application, as it would whether Qt or not, and it not recommended for Qt applications. -
@ocgltd Properly clean up and delete your objects before you leave main()
-
@Christian-Ehrlicher My class is created on the stack, so I don't think there is more I can do to clean up. I tried putting my class creation inside another nested block as per below, but I still don't see the qDebug messages upon exit.
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); { MyClass myclass; QTimer::singleShot(20000, []() { exit(0); } ); return a.exec(); } }
-
You call the systems exit() function so there is no cleanup done as described in the c++ documentation: https://en.cppreference.com/w/cpp/utility/program/exit
Properly close the Qt app with QCoreApplication::quit()
-
@Christian-Ehrlicher That worked as expected. I checked the quit docs and it's not clear how/when I should use this.
Is this a replacement for exit() only? Should this be the last line of every Qt program? What's the right way to use this method?
-
@ocgltd said in How process remaining events before shutdown:
hat's the right way to use this method?
You should use it when you want to properly shut down your application.
-
@ocgltd
Basically once you are insideQCoreApplication::exec()
that is when you should always useQCoreApplication::quit()
. This does not actually exit the application, rather it exits thea.exec()
you have. Code then executes anything after that in your call, which is usually nothing, as in yourreturn a.exec();
being the final statement in yourmain()
function.Using
QCoreApplication::quit()
(or more rarelyQCoreApplication::exit()
) exits the Qt application event loop "cleanly", and allows proper clean up. Using the non-Qt systemexit()
directly exits the C++ application, as it would whether Qt or not, and it not recommended for Qt applications. -