Qt World Summit: Submit your Presentation

Serialization and deserialization of a list of custom structures (QSettings?)

  • Hi!

    I'm writing an application which, so far, has used QSettings to store its current configuration into INI files. (The requirement is that the configuration needs to be swappable).

    This worked reasonably well, but now I need to store a list of custom structures, and I'm not sure how to go about it. Can I use Qt's metatype system and just put a QList<MyStruct> into the QSettings? Or do I abandon QSettings and write my own XML/INI/whatever serializer/deserializer?

    Thanks in advance!

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Yes you can put your custom struct in QSettings but you have to do some work for it. Essentially you have to write the QDataStream operators for MyStruct and register them with qRegisterMetaTypeStreamOperators so that QVariant can use them to do the serialization/deserialization for you. You don't need to create operators for QList<MyStruct>. Qt's smart enough to use the MyStruct stream operators with it's container classes.

  • Hi, thank you for the response!

    Unfortunately, when I try to save a QList<MyStruct>, I get the following error at runtime:

    QVariant::save: unable to save type 'QList<Action>' (type id: 1032).
    ASSERT failure in QVariant::save: "Invalid type to save", file kernel\qvariant.cpp, line 2124
    Invalid parameter passed to C runtime function.

    This is even though I have (after some wrestling) managed to successfully save a Action (MyStruct) using QVariant::fromValue(), having registered both Action as a metatype as well as its operators in main():


    Any idea why that might be?

    edit: A-ha! For future reference, it isn't needed to create custom operators for QList<MyStruct>, but it's still required to call qRegisterMetaTypeStreamOperators() on QList<MyStruct>. Solved!