[SOLVED] Saving and reading QMap from QSettings



  • Hello,

    I'm trying to store a QMap<QString, QString> to QSettings as bytearray, and then read it back as a QMap object. Here's what I got so far:

    QMap<QString,QString> is typedefd as QStringMap

    Saving, works:
    @
    ...
    QStringMap testmap;
    testmap.insert("M1", "Value 1");
    testmap.insert("M2", "Value 2");

    QByteArray data;
    QDataStream *stream = new QDataStream(&data, QIODevice::WriteOnly);
    
    *stream << testmap;
    delete stream;
    
    program_settings.setValue("savedMap", data);
    

    ...
    @

    So, this saves the QByteArray to QSettings object with key savedMap. My question is, how do I read construct a QMap from the bytearray stored in the QSettings? I presume I need to use the Related Non-Members:

    @QDataStream & operator<<(QDataStream & out, const QMap<Key, T> & map)
    QDataStream & operator>>(QDataStream & in, QMap<Key, T> & map)@

    found in the QMap documentation, but to be honest I don't know how! Anyone?



  • I think you need to read setting to QByteArray, create QDataStream from QByteArray and read QMap from QDataStream.
    Not tested example
    @
    QByteArray data = program_settings.value("savedMap").toByteArray();
    QDataStream *stream = new QDataStream(&data, ReadOnly);
    QStringMap testmap;
    stream >> testmap;
    @



  • [quote author="andreyc" date="1409247208"]I think you need to read setting to QByteArray, create QDataStream from QByteArray and read QMap from QDataStream.
    Not tested example
    @
    QByteArray data = program_settings.value("savedMap").toByteArray();
    QDataStream *stream = new QDataStream(&data, ReadOnly);
    QStringMap testmap;
    stream >> testmap;
    @
    [/quote]

    Thank you! I actually got as far as the last line, somehow just couldn't figure out to use the >> operator (which is ironic, as it's very logical >.< Haven't used streams too much yet..)

    So, tested sample snippets:

    Writing:
    @
    QStringMap testmap;
    testmap.insert("M1", "Value 1");
    testmap.insert("M2", "Value 2");
    QByteArray data;
    QDataStream stream(&data, QIODevice::WriteOnly);
    stream << testmap;
    program_settings.setValue("savedMap", data);
    @

    Reading:
    @
    QStringMap readMap;
    QByteArray readData = program_settings.value("savedMap").toByteArray();
    QDataStream readStream(&readData, QIODevice::ReadOnly);
    readStream >> readMap;
    @

    I only used new operator when creating the QDataStream, because an found an example for the writing which said it was needed. But as I tested, it worked just fine like the examples above.

    Thank you very much!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.