Search code examples
c++eventsqtsignals-slots

Qt - How to intercept the application's close event (if there's one)


I need to do some work right before my application closes (note that I said my application and not it's main window). Is there an application close event or any other way to accomplish this?

The reason that I can't rely on the main window's close event is that my application runs on the background leaving a system tray icon.


Solution

  • Your application is likely derived from QApplication. You could put your cleanup code in the destructor of your application:

    class MyApp: public QApplication {
    public:
        ~MyApp() {
            // cleanup code here
        }
    };
    

    Or, in your main(), you probably have something like this:

    int main(int argc, char *argv[]) {
        MyApp a(argc, argv);
        return a.exec();
    }
    

    You can do work after calling exec():

    int main(int argc, char *argv[]) {
        MyApp a(argc, argv);
        int r = a.exec();
        // cleanup code here
        return r;
    }