Johan Råde
Johan Råde

Reputation: 21418

QApplication::saveState and QApplication::commitData on Windows

When are the virtual functions QApplication::saveState and QApplication::commitData called on Windows? Are they called at all, or is session management just a UNIX thing? Are they called if the app is running when the user logs out (and the app is forcibly shut down)?

Upvotes: 2

Views: 1332

Answers (2)

Johan Råde
Johan Råde

Reputation: 21418

I wrote a simple test app; see below. I compiled the app with Qt 4.7 and MSVS 2010 and ran it on Windows XP. Then I ran three different tests:

  1. Start the app. Terminate the app using the close button in the main window.
  2. Start the app. Terminate the app using End Task in the Task Manager.
  3. Start the app. Log out with the app running.

Result of the tests:

  • QApplication::commitData is called only in case 3
  • QApplication::saveState is not called in any of the three cases.

Here is the code for the test app. The commitData and saveState functions don't do anything useful; the only purpose of the app is to check whether they are called or not.

#include <QtCore/QtCore>
#include <QtGui/QtGui>
#include <fstream>

class MyApplication : public QApplication {
public:
    MyApplication(int& argc, char** argv) : QApplication(argc, argv) {}

    virtual void saveState(QSessionManager& manager)
    {
        std::ofstream ofs("SaveState.txt");
        ofs << "Test";
    }

    virtual void commitData(QSessionManager& manager)
    {
        std::ofstream ofs("CommitData.txt");
        ofs << "Test";
    }
};

int main(int argc, char** argv)
{
    {
        std::ofstream ofs("Begin.txt");
        ofs << "Test";
    }

    MyApplication app(argc, argv);
    QMainWindow mw;
    mw.show();
    app.exec();

    {
         std::ofstream ofs("End.txt");
         ofs << "Test";
    }
}

Upvotes: 4

Kaleb Pederson
Kaleb Pederson

Reputation: 46489

From the documentation:

Getting Session Management to Work with Qt

Start by reimplementing QApplication::commitData() to enable your application to take part in the graceful logout process. If you are only targeting the Microsoft Windows platform, this is all you can and must provide. (emphasis added)

commitData() is called when a windows application receives the WM_QUERYENDSESSION windows message.

From the WM_QUERYENDSESSION docs:

The WM_QUERYENDSESSION message is sent when the user chooses to end the session or when an application calls one of the system shutdown functions. If any application returns zero, the session is not ended. The system stops sending WM_QUERYENDSESSION messages as soon as one application returns zero.

After processing this message, the system sends the WM_ENDSESSION message with the wParam parameter set to the results of the WM_QUERYENDSESSION message.

http://doc.qt.nokia.com/latest/qapplication.html#commitData

Upvotes: 2

Related Questions