user63898
user63898

Reputation: 30925

QSettings how to save QMap<QString,int> into configuration file

After reading Save QList<int> to QSettings, I'm tring to do the same with QMap<QString,int>. I would like the configuration file to look like this:

1111=1  
2222=3  
4444=0  

But I'm getting a compilation error:

Q_DECLARE_METATYPE(QMap<QString,int>)

Warning C4002: too many actual parameters for macro 'Q_DECLARE_METATYPE'
ConfigSettings.h(5) : error C2976: 'QMap' : too few template arguments

Upvotes: 5

Views: 7615

Answers (4)

Yevgeniy Logachev
Yevgeniy Logachev

Reputation: 761

QSetting accept QVariant type to pass into setValue method, so it means that you can store QMap<QString, QVarint> map directly to settings

// Store
QMap<QString, QVariant> storeMap;
QMapIterator it(myMap);
// iterate through the map to save the values in your chosen format
while(it.hasNext())
{
    storeMap[it.key()] = QVariant(it.value());
    it.next();
}
settings.setValue("myKey", storeMap);

..
// Read
QMap<QString, QVariant> readMap = settings.value("myKey").toMap();
QMapIterator it(readMap);
while(it.hasNext())
{
    myMap[it.key()] = it.value().toInt();
    it.next();
}

Upvotes: 3

guitarpicva
guitarpicva

Reputation: 441

I understand the accepted answer, but I think the original question was how to store the QMap. It devolved into how to make the compiler behave.

QSettings mySettings...
QMapIterator it(myMap);
// iterate through the map to save the values in your chosen format
while(it.hasNext())
{
    it.next();
    mySettings.setValue(it.key(), it.value());
}

If however you wish to store this along with a bunch of other settings or data structures, you might consider using "beginGroup()" and "endGroup()" to group a bunch of different data structures into one file. Very tidy and readable.

Upvotes: 0

Aditya
Aditya

Reputation: 123

Like Mat said, the error is caused by the preprocessor not understanding templates. However, you can easily fix this via a simple typedef.

typedef QMap<QString,int> QIntMap
Q_DECLARE_METATYPE(QIntMap)

Upvotes: 6

Mat
Mat

Reputation: 206861

The error message you're getting is caused by the fact that the preprocessor doesn't know about templates. So it's parsing that macro call is if it had two arguments - QMap<QString and int>, which makes no sense.

To save the data as you want it, you're better of serializing it yourself to your QSettings. Something like this for writing:

settings.beginGroup("Whatever");
QMap<QString, int>::const_iterator i = map.constBegin();
while (i != map.constEnd()) {
     settings.setValue(i.key(), i.value());
     ++i;
 }
settings.endGroup();

To read the settings, use the same approach with the help of the childKeys() function.

settings.beginGroup("Whatever");
QStringList keys = settings.childKeys();
foreach (QString key, keys) {
     map[key] = settings.value(key).toInt();
}
settings.endGroup();

Upvotes: 15

Related Questions