There are two possible ways:
- load all settings into some struct
- load values on-demand
Which approach is better?
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.)
In the documentation of QSettings
, it says that it has been optimized really well.
Internally, it keeps a map of QStrings to QVariants. All the accessor methods are extremely useful and are easy to use.
When I have used QSettings
, I set it up similarly to their example with readSettings()
and writeSettings()
functions. See this example about half way down the page.
The moment I call readSettings()
the QSettings object gets created it loads the values on demand and it keeps all the settings in some struct.
So in my main function I make sure I set up my application name and my organization name, and I also use QSettings::setFormat
, and then after that whenever I want to access QSettings, I create an instance of QSettings with default parameters and access the settings.
QSettings s;
int val = s.value("Some_Group/some_setting", default_value).toInt();
// ...
s.setValue("Some_Group/some_setting", val);
来源:https://stackoverflow.com/questions/14365653/how-to-load-settings-in-qt-app-with-qsettings