PDA

View Full Version : QSettings again ... how to remove array elements



Mike
10th January 2006, 22:13
Hi all,

I would like to store some data structured as an array. That's working, and my settings file contains something like:


[blogAccounts]
1\accountName=Test 1
1\userName=Mike
1\userPassword=secret
2\accountName=Test 2
2\userName=Mike
2\userPassword=secret
size=2


Now I use this code to remove the first item, and let's assume that the currentAccountName contains the first entry of the array:


...
// Ok, we need to find the right account...
QSettings settings("MKrueger", "MKBlog");
int size = settings.beginReadArray("blogAccounts");
bool didRemove = false;
for (int i = 0; i < size; ++i)
{
// Select the data set
settings.setArrayIndex(i);
// Now compare the account name with the one selected...
if (_currentAccountName == settings.value("accountName").toString())
{
// This is the one we need to remove...
settings.endArray();
// Now reopen the settings for writing...
settings.beginWriteArray("blogAccounts");
// select the desired account again
settings.setArrayIndex(i);
// and now remove it...
settings.remove("");
didRemove = true;
break;
}
}
settings.endArray();

if (false == didRemove)
return; // Unable to remove account


The result in my settings file is this:


[blogAccounts]
2\accountName=Test 2
2\userName=Mike
2\userPassword=secret
size=1


If I now try to load the remaining account it fails. I suspect because the prefix is still 2 and not 1. Would that assumption be correct?
If so, how should I remove an item correctly? Do I have to remove the complete array and then write it out again?

Thanks...

Mike
10th January 2006, 22:23
In addition to the above, I also found out, that if I remove the last array item, then the size value will still be 1, and not 0 - which I would have expected.
I start to believe I should use something else for storing my data, or am I doing something completely wrong here?

wysota
10th January 2006, 23:53
Why not rewrite the array from the beginning so that indexes start from the beginning (1) again?

Mike
11th January 2006, 08:50
... well yes, I guess that's a solution. I just thought that if QSettings offers the option to remove items from the array, then it should handle it the right way. Since this doesn't seem to be the case, I would consider this a bug...
I guess what I need to do is to remove the whole section (or group). Hopefully that will work, and then write out a new array as you suggested. I will try that later today...

wysota
11th January 2006, 09:58
It doesn't offer removing an item from array, it offers removing an item (in general). Array differs from "regular" elements only that QSettings has a "smart" function to operate on them but they are really usual entries.