Use qRegisterMetaTypeStreamOperators<YourType>("YourType")
to enable serialization/de-serialization of custom types with QVariant. This function registers your type's QDataStream input/output functions with Qt's metatype system so that it can invoke them when saving/loading a variant containing your custom type.
#include <QtCore/QDebug>
#include <QtCore/QDataStream>
#include <QtCore/QSettings>
struct CustomType {
QString name;
int age;
};
Q_DECLARE_METATYPE(CustomType);
QDataStream& operator<<(QDataStream& out, const CustomType& v) {
out << v.name << v.age;
return out;
}
QDataStream& operator>>(QDataStream& in, CustomType& v) {
in >> v.name;
in >> v.age;
return in;
}
int main(int,char**) {
qRegisterMetaTypeStreamOperators<CustomType>("CustomType");
{
CustomType t;
t.name = "John Smith";
t.age = 42;
QSettings s("config.ini", QSettings::IniFormat);
s.setValue("user", QVariant::fromValue(t));
}
{
QSettings s("config.ini", QSettings::IniFormat);
QVariant value = s.value("user");
CustomType t = value.value<CustomType>();
qDebug() << t.name << t.age;
}
return 0;
}