Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to save QMap



  • Hello guys, can u show me how I can save QMap using QFile?

    I'm trying to use keys and values, but I'm doing this wrong.

    QFile file(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "test.txt");
        if (file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
                QTextStream stream(&file);
               for (int i=0;i<DailyTaskMap.count();i++)
               {
                   //stream << DailyTaskMap.key() <<"\n"; 
                   //stream << DailyTaskMap.value() <<"\n";
                   qDebug() << "SAVED";
               }
        }
        else
            qDebug() <<file.errorString();
    

  • Lifetime Qt Champion

    @naax said in How to save QMap:

    I will use .txt file

    Does not answer my question: how will the file content look like?

    Please read documentation to see how to iterate over a QMap (https://doc.qt.io/qt-5/qmap.html):

    QMap<QString, int>::const_iterator i = map.constBegin();
    while (i != map.constEnd()) {
        cout << i.key() << ": " << i.value() << Qt::endl;
        ++i;
    }
    

  • Lifetime Qt Champion

    @naax What should be the format? This is something you need to decide bafore implementing anything? So, how should the file look like after saving?
    And shouldn't this DailyTaskMap.key() be

    DailyTaskMap[i].key()
    

    ?



  • @jsulm

    I will use .txt file.

    DailyTaskMap[i].key() ?
    

    I tried this. I don't know how I can write this code correctly.

    ss.png


  • Lifetime Qt Champion

    @naax said in How to save QMap:

    I will use .txt file

    Does not answer my question: how will the file content look like?

    Please read documentation to see how to iterate over a QMap (https://doc.qt.io/qt-5/qmap.html):

    QMap<QString, int>::const_iterator i = map.constBegin();
    while (i != map.constEnd()) {
        cout << i.key() << ": " << i.value() << Qt::endl;
        ++i;
    }
    


  • @jsulm

    Thanks, bro a lot. Have a nice day!



  • The more general term for this is object serialization: translating the object into a well defined format that can be saved to disk or transfered across a network. I'd advise that instead of reinventing and coming up with a custom format. You should review existing formats like XML or JSON, and if appropriate, then acquire or write translators to go between native format and the "serialized" format. Qt already has some serialization capabilities but I don't use them so I'm not sure what specifically exists.


Log in to reply