Restore geometry and state of an arbitrary QDialog

561 Views Asked by At

In our applications we are using customizable dialogs using exhaustively QSplitter, so that our customers can rearrange the dialogs to fit their needs.

(Sometimes we are also using QDockWidget, but this seems to be similar.)

Now, it is very annoying to rearrange the dialog every time it is opened again. Or even between different starts of the program.

After consulting the documentation I was able to restore the state and the geometry of a specific dialog containing one QSplitter.

#include <QApplication>
#include <QLabel>
#include <QDebug>
#include <QSplitter>
#include <QPushButton>
#include <QTextEdit>
#include <QDialog>
#include <QSettings>
#include <QHBoxLayout>

int main(int argc, char** args) {
    QApplication app(argc, args);
    app.setOrganizationName("Tech");
    app.setOrganizationDomain("qt.us");
    app.setApplicationName("RestoreLayout");
    app.setApplicationVersion("1.0");
    QDialog dialog;
    dialog.setLayout(new QHBoxLayout);
    auto splitter = new QSplitter;
    splitter->addWidget(new QLabel("Left"));
    splitter->addWidget(new QLabel("Right"));
    dialog.layout()->addWidget(splitter);
    auto accept = new QPushButton("Accept");
    accept->connect(accept, &QPushButton::clicked, [&](){
        dialog.accept();
    });
    splitter->addWidget(accept);
    auto geom= QSettings().value("Geom").toByteArray();
    auto splitterState = QSettings().value("State").toByteArray();
    qDebug() << geom;
    qDebug() << splitterState;
    dialog.restoreGeometry(geom);
    splitter->restoreState(splitterState);
    dialog.show();
    dialog.connect(&dialog, &QDialog::accepted, [&]() {
        QSettings().setValue("Geom", dialog.saveGeometry());
        QSettings().setValue("State", splitter->saveState());
        app.quit();
    });
    app.exec();
}

Unfortunately, this seems to be an approach, which is not usable in general.

Assume, that there is some arbitrary dialog, that needs to restore its geometry and state. Even worser QSplitter and QDockWidget might be even used in a nested fashion, which is done in our applications.

How can an outside programmer restore the geometry and the state of a arbitrary dialog that might be easily applicable to all possible dialogs?

1

There are 1 best solutions below

0
On

For saving states of QDockWidget each it must be named: dockWidgetN->setObjectName("dock-widget-N");

But you can save only QMainWindow state for saving states of docks in this window.

You can separatelly save states via QSettings (it's QByteArray) and use some one state for many windows.

See here: How to save state of a dialog in Qt?