How to properly use QSettings
qsettings, qt
Solution
I would do it like this:
Lets say that we have two functions member of a class to load and save the scores. To use the registry, you have to specify the application name and editor:
QSettings settings("<MyEditorName>","<myAppName>");
saveScores(settings);
loadScores(settings);
to use a file, you have to provide the file path and format:
QSettings settings("<filepath>",QSettings::iniFormat);
saveScores(settings);
loadScores(settings);
from your code and the documentation; the member function would be as follow. The class countains a vector of scores (QVector mScores)
Function to save the scores:
void myClass::saveScores(QSettings& iSettings)
{
iSettings.beginGroup("Scores");
iSettings.beginWriteArray("results");
for(int i=0; i<mScores.count();i++)
{
iSettings.setArrayIndex(i);
iSettings.setValue("result",mScores[i]);
}
iSettings.endArray();
iSettings.endGroup();
}
Function to load the scores
void myClass::loadScores(QSettings& iSettings)
{
iSettings.beginGroup("Scores");
int size = iSettings.beginReadArray("results");
mScores.resize(size);
for(int i=0;i<size;i++)
{
iSettings.setArrayIndex(i);
mScores[i] = iSettings->value("results").toInt();
}
iSettings.endArray();
iSettings.endGroup();
}
I am using groups to provide better visibility in the saving file but you can remove them
Problem
I want to use `QSettings` to save highscores but it doesn't work properly. I'm saving and reading those values in 2 different files. This is my code responsible for adding values into array: ``` QSettings settings; settings.beginWriteArray("results"); int size = settings.beginReadArray("results"); settings.setArrayIndex(size); settings.setValue("result", "qwerty"); ``` and reading: ``` QSettings settings; QString tmp = ""; int size = settings.beginReadArray("results"); for(int i = 0; i < size; ++i) { settings.setArrayIndex(i); tmp += settings.value("result").toString(); } ui->label->setText(tmp); ```