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);
QSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner. It also supports custom storage formats. QSettings's API is based on QVariant, allowing you to save most value-based types, such as QString, QRect, and QImage, with the minimum of effort.
Bookmark this question. Show activity on this post. According to Qt's docs for the latest Qt version, looking at QSettings, they say that system scope of settings on a Mac are stored in a directory /etc/xdg.
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
The beginReadArray() after beginWriteArray() is causing the problem. Do this:
QSettings settings;
int size = settings.beginReadArray("results");
settings.endArray();
settings.beginWriteArray("results");
settings.setArrayIndex(size);
settings.setValue("result", "qwerty");
settings.endArray();
Note you need to call endArray() when finished.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With