PDA

View Full Version : Where to save QSettings?



arcull
22nd July 2015, 08:04
Hi all.

I'm working on a little destkop gui app and use QSettings to save settings to ini file, so they can be loaded on next app run. I have some lineEdit components on form where user puts settings, so to load settings I call my method to load settings from the MainWindow constructor, but don't know where to call my save settings method. I know I could make a separate button ("Save settings") for this, but would rather have it triggered somewhere automatically. I can not save settings on MainWindow destructor, where would you put it, much thanks.

anda_skoa
22nd July 2015, 08:34
You could overwrite the main window's closeEvent().
Or in main(), not return directly from app.exec() but keep its return value in a local variable, then save then return the variable.

Cheers,
_

arcull
22nd July 2015, 08:51
You could overwrite the main window's closeEvent().
Or in main(), not return directly from app.exec() but keep its return value in a local variable, then save then return the variable.

Cheers,
_ Thanks, window's closeEvent() sounds more appropriate to me, but where do find it or how do I make it, thanks

mikag
22nd July 2015, 11:50
Just override the closeEvent in your ManiWindow class

mainwindow.h

void closeEvent(QCloseEvent* event) override;
(btw. the override specifier requires a C++ 11 compatible compiler, should not be much of a problem any longer though)

maniwindow.cpp

void MainWindow::closeEvent(QCloseEvent* event)
{
...
}

arcull
22nd July 2015, 12:58
mikag thanks, solved

d_stranz
23rd July 2015, 18:43
You can also write the QSettings entry immediately after the user finishes editing the QLineEdit. I do this when the settings I need are "local" to that piece of code, and I don't want to have to propagate that throughout the app. For example, I have a dialog that is used to edit properties for a plot; when the user closes the dialog after editing, I immediately write the changes out to QSettings. The rest of the app doesn't have to know.

Some people may not like this style, but I find it is useful for creating reusable components that don't depend on other parts of the app in order to function correctly.