c++serializationqlistqmapqsettings

How to save QList<QMap> into QSettings file


I have a large amount of data stored in a variable of type QList<QMap<QString,float>> and I need to save the variable to easily retrieve it. I want to save it into a file with QSettings but with no luck. How can I do this?


Solution

  • In order to save some type of data QSettings uses QDataStream so you must implement it for QMap <QString, float>, in addition to registering it using qRegisterMetaTypeStreamOperators.

    #include <QCoreApplication>
    #include <QSettings>
    #include <QDebug>
    #include <QDataStream>
    
    #ifndef QT_NO_DATASTREAM
    QDataStream &operator<<(QDataStream &stream, const QMap<QString,float> &map)
    {
        QMap<QString, float>::const_iterator i = map.constBegin();
        while (i != map.constEnd()) {
            stream << i.key() << i.value();
            ++i;
        }
        return stream;
    }
    QDataStream &operator>>(QDataStream &stream, QMap<QString,float> &map)
    {
        QString key;
        float value;
        stream >> key;
        stream >> value;
        map[key] = value;
        return stream;
    }
    #endif
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        qRegisterMetaTypeStreamOperators<QMap<QString,float>>("QMap<QString,float>");
        qRegisterMetaTypeStreamOperators<QList<QMap<QString,float>>>("QList<QMap<QString,float>>");
        {
            QSettings settings;
            QList<QMap<QString,float>> l;
            for(int i=0; i<3; i++){
                QMap<QString, float> map;
                map["a"] = 0.1*(i+1);
                map["b"] = 0.2*(i+1);
                map["c"] = 0.3*(i+1);
                l<< map;
            }
            QVariant v = QVariant::fromValue(l);
            settings.setValue("val", v);
        }
        {
            QSettings settings;
            QVariant v = settings.value("val");
            QList<QMap<QString,float>> l = v.value<QList<QMap<QString,float>>>();
            int j=0;
            for(const QMap<QString, float> &map: l ){
                 qDebug()<< "index: " << j;
                QMap<QString, float>::const_iterator i = map.constBegin();
                while (i != map.constEnd()) {
                    qDebug() << i.key() << ": " << i.value();
                    ++i;
                }
                j++;
            }
        }
        return 0;
    }
    

    Output:

    index:  0
    "a" :  0.1
    "b" :  0.2
    "c" :  0.3
    index:  1
    "a" :  0.2
    "b" :  0.4
    "c" :  0.6
    index:  2
    "a" :  0.3
    "b" :  0.6
    "c" :  0.9