How to load settings in Qt app with QSettings
It depends on the way you will use your settings file. Do you want to allow the user of your application to dynamically change the settings in the file (.ini file for example) ? Or the settings have to be set by the GUI ?
If you are using some GUI to change the settings, I advice you you to load the main settings at the start of your application from a static class for example.
void SettingsManager::loadSettings()
{
// .ini format example
QSettings settings(FileName, QSettings::IniFormat);
IntegerSetting = settings.value("SettingName", default).toInt();
BooleanSetting = settings.value("SettingName", default).toBool();
// ...
}
Then, there is no problem to save your changed values on-demand because of the QSettings optimization.
/**
* key is your setting name
* variant is your value (could be string, integer, boolean, etc.)
*/
void SettingsManager::writeSetting(const QString &key, const QVariant &variant)
{
QSettings settings(FileName, QSettings::IniFormat);
settings.setValue(key, variant);
}
If you're concerned, you could put each logical group of settings behind an interface. Then, build a concrete class that uses QSettings to retrieve settings on demand.
If you find that to be a performance bottleneck, build a concrete class that caches the settings. (I never have needed to do so. QSettings has always been fast enough.)