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

After reading Save QList<int>UpQSettings , I 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 get 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
+5
source share
4 answers

The error message you receive is caused by the fact that the preprocessor does not know about the templates. Thus, the parsing of this macro occurs if it has two arguments - QMap<QStringand int>that does not make sense.

To save data on your own, you better serialize it yourself on 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();

, childKeys().

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

Mat, , . typedef.

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

QSetting QVariant , setValue, , QMap<QString, QVarint>

// 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();
}
+1

, , , QMap. , .

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());
}

, "beginGroup()" "endGroup()", . .

0

All Articles