7

I have a Qt gui application that uses dock widgets and similar items, which user can adjust themselves.

I want the layout to stay on application restart. The application already has some functions to save and load user configuration, but I have no idea how would I store a layout (positions of docks, their size etc), neither how would I restore them.

Is there any easy way of doing this? Or do I have to check the size, position and location of every single element and store it separately?

Petr
  • 13,747
  • 20
  • 89
  • 144

1 Answers1

10

For storing your dock windows layout you can use QMainWindow::saveState(int version) and QMainWindow::restoreState(const QByteArray &state, int version) in combination with QSettings class.

Example from Qt docs:

void MyMainWindow::closeEvent(QCloseEvent *event)
{
    QSettings settings("MyCompany", "MyApp");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
    QMainWindow::closeEvent(event);
}
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • does it have to be inside of QSettings? My application uses xml to store the configuration. – Petr Oct 18 '13 at 09:07
  • 1
    @Petr: using `QSettings` is not a requirement. You can store the byte array in the format and file that is most convenient for you. The main point is using `saveState()` and `restoreState()` functions that use `QByteArray`. – vahancho Oct 18 '13 at 09:09
  • it just don't work :( should I first create gui and then call it or call it and then create gui? (I didn't make the layout of dock widgets in visual editor, but it's in source code) – Petr Oct 18 '13 at 09:38
  • @Petr: you need to create your GUI first (tool bars, dock windows, etc.). Than get the state with `saveState()` function and store it. On next session (when you start your GUI) you need to create your GUI and call `restoreState()` with the saved byte array. It doesn't meter how you create your dock windows: in visual editor or with API. – vahancho Oct 18 '13 at 09:43
  • that's precisely how I do that, saveState produces empty array, saveGeometry produces some binary data, but after I load them nothing happens – Petr Oct 18 '13 at 09:46
  • @Petr: Do you have your parent-child relationships set correctly? – arne Oct 18 '13 at 09:50
  • Ok it seems to work now, it just doesn't seem to store the width of some components, otherwise it's ok – Petr Oct 18 '13 at 10:09
  • More at https://stackoverflow.com/questions/14288635/any-easy-way-to-store-dock-widows-layout-and-sizes-in-settings-with-qt – Rafe Sep 04 '17 at 23:51