Save QList<QStringList> using QSettings?



  • Hi guys!

    I wonder if i can somehow save a QList<QStringList> using QSettings. So far all my attempts did fail. My last hope was QVariant but i only get a C2440 "cannot convert 'QList<QStringList>' to 'QVariant' if i try "QVariant list = myList;". Did find some examples out there to save a QList using QVariant but non of then are using QStringList.

    I also did "Q_DECLARE_METATYPE(QList<QStringList>)" and

    // save list
    setup.setValue("mylist", QVariant::fromValue(myList));
    
    // load list
    QList<QStringList> myList = setup.value("mylist").value<QList<QStringList> >();
    
    

    But the list is always empty.

    Is there a way to save a QList<QStringList>?

    I'm using Qt 5.7.0.

    Thanks!


  • Moderators

    You don't need to use Q_DECLARE_METATYPE for this. The QList<T> types are automatically registered (as documented here ). What you need is to register the streaming operators for that type, because that is not done automatically. See qRegisterMetaTypeStreamOperators.

    Here's an example:

    int main(int argc, char *argv[])
    {
        qRegisterMetaTypeStreamOperators<QList<QStringList>>("Stuff");
        QList<QStringList> data {{"hello", "world"}, {"how", "are", "you"}};
    
        QSettings setup("C:/stuff.ini", QSettings::IniFormat);
        setup.setValue("mylist", QVariant::fromValue(data));
        QList<QStringList> data2 = setup.value("mylist").value<QList<QStringList>>();
    
        qDebug() << data;
        qDebug() << data2;
    }
    

    Prints as expected:

    (("hello", "world"), ("how", "are", "you"))
    (("hello", "world"), ("how", "are", "you"))
    


  • Thank you!

    Your example works as expected but i still don't get my own code to read the data. Saving works so far. My guess is it is because by QList<QStringList> myList gets gets set before the meta type is set. I need to access the QList in a lot of functions so i did set it up as private: QList<QStringList> myList.

    So i guess my final question is where to place the qRegisterMetaTypeStreamOperators<QList<QStringList>>("myList"); code? Is it possible reg. the meta type before the main header file is included or some other way to get this working?

    Thanks!



  • I just had a typo in the group ^^
    Sorry!