10.3.  QSettings: Saving and Restoring Application State

[ fromfile: qsettings.xml id: qsettings ]

Example 10.7. src/widgets/mainwindow/mainwindow-main.cpp

#include "mymainwindow.h"
#include <QApplication>

int main( int argc, char ** argv ) {
    QApplication app( argc, argv );
    app.setOrganizationName("objectlearning");
    app.setOrganizationDomain("objectlearning.net");
    app.setApplicationName("mainwindow-test");
    MyMainWindow mw;
    mw.show();
    return app.exec();
}

Example 10.8. src/widgets/mainwindow/mymainwindow.cpp

[ . . . . ]

void MyMainWindow::readSettings() {
    QSettings settings;
    QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
    QSize size = settings.value("size", QSize(400, 400)).toSize();
    QByteArray state = settings.value("state", QByteArray())
                                                   .toByteArray();
    restoreState(state);
    resize(size);
    move(pos);
}

Example 10.9. src/widgets/mainwindow/mymainwindow.cpp

[ . . . . ]

void MyMainWindow::closeEvent(QCloseEvent* event) {
    if (maybeSave()) {
        writeSettings();
        event->accept();
    } else {
        event->ignore();
    }
}


void MyMainWindow::writeSettings() {
    /* Save postion/size of main window */
    QSettings settings;
    settings.setValue("pos", pos());
    settings.setValue("size", size());
    settings.setValue("state", saveState());
}