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 theQSettings
? Or do I abandonQSettings
and write my own XML/INI/whatever serializer/deserializer?Thanks in advance!
-
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 forQList<MyStruct>
. Qt's smart enough to use theMyStruct
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
) usingQVariant::fromValue()
, having registered bothAction
as a metatype as well as its operators inmain()
:qRegisterMetaType<Action>("Action"); qRegisterMetaTypeStreamOperators<Action>("Action");
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 callqRegisterMetaTypeStreamOperators()
onQList<MyStruct>
. Solved!