Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Final task upon program termination



  • Hello,

    I was wondering if there is a way to run a final function call/ slot when a program terminates. I have a json file with data that is being updated and read from. When the program ends (user stops running program) I want to reset the data withing the file. Is there any type of signal slot that you be used right before before terminates?



  • Does you main.cpp look something like this?

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    
        QGuiApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                         &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
        engine.load(url);
    
        return app.exec();
    }
    

    Then change the return statement to something like this:

    auto ret = app.exec()
    
    // your final code here
    finalfunction();
    
    return ret;
    
    


  • Does you main.cpp look something like this?

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    
        QGuiApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                         &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
        engine.load(url);
    
        return app.exec();
    }
    

    Then change the return statement to something like this:

    auto ret = app.exec()
    
    // your final code here
    finalfunction();
    
    return ret;
    
    


  • @fcarney Sweet! That worked, thanks.