With beginReadArray() it should be possible to read a block from an ini file dynamically.
I would like to read the entries in the block [colordefs]
dynamically, because there can be any number of color definitions.
The block [colors]
has a fixed length. When reading in these values, the color name should replaced by the color value from [colordefs]
.
[colordefs]
colors/white = "#ffffff";
colors/grey = "#c3c3c3";
colors/lightGrey = "#f0f0f0";
colors/darkGrey = "#a0a0a0";
colors/darkerGrey = "#808080";
colors/mint = "#30dccc";
[colors]
colors/security/passwordEnabled = "mint"
colors/security/passwordDisabled = "grey"
colors/display/backgroundDefault = "white"
colors/display/backgroundHeader = "grey"
colors/display/backgroundFooter = "grey"
I have tried different examples but I always get a size of 0
settings->beginGroup("colordefs");
int size = settings->beginReadArray("colors");
for (int i = 0; i < size; i) {
settings->setArrayIndex(i);
}
settings->endGroup();
Any idea?
CodePudding user response:
beginReadArray()
returns 0
because you don't actual have an array in your settings file. Arrays in the settings file look like this
[logins]
1\password=123
1\userName=test
2\password=bar
2\userName=foo
size=2
Have a look at the documentation. These settings were generated by the following snippet.
QSettings settings("myapp.ini", QSettings::IniFormat);
struct Login
{
QString userName;
QString password;
};
QList<Login> logins = {{"test", "123"}, {"foo", "bar"}};
settings.beginWriteArray("logins");
for (int i = 0; i < logins.size(); i) {
settings.setArrayIndex(i);
settings.setValue("userName", logins.at(i).userName);
settings.setValue("password", logins.at(i).password);
}
settings.endArray();
If you want to get all keys you can use the following code.
QStringList keys = settings.allKeys();
for (const auto &k : keys)
qDebug() << k;
Which in your case will give you
"colordefs/colors/darkGrey"
"colordefs/colors/darkerGrey"
"colordefs/colors/grey"
"colordefs/colors/lightGrey"
"colordefs/colors/mint"
"colordefs/colors/white"
"colors/colors/display/backgroundDefault"
"colors/colors/display/backgroundFooter"
"colors/colors/display/backgroundHeader"
"colors/colors/security/passwordDisabled"
"colors/colors/security/passwordEnabled"
With the key you can then use value()
to get the value behind the key.
You can also get all the keys of certain group by using
settings.beginGroup("colordefs");
QStringList keys = settings.allKeys();
for (const auto &k : keys)
qDebug() << k;
settings.endGroup();
Which in your case will give you
"colors/darkGrey"
"colors/darkerGrey"
"colors/grey"
"colors/lightGrey"
"colors/mint"
"colors/white"