Saving custom structures and classes to QSettings
Overview[edit | edit source]
Custom types registered using qRegisterMetaType() and qRegisterMetaTypeStreamOperators() can be stored using QSettings.
Detailed description[edit | edit source]
In header file structure (or class) have to be declared and registered as metatype. A type can be registered as metatype as long as it provides a public default constructor, a public copy constructor and a public destructor.
struct CustomStructure
{
QString A;
QString B;
};
Q_DECLARE_METATYPE(CustomStructure)
In application metatype must be registered during run-time
qRegisterMetaType<CustomStructure>("CustomStructure");
qRegisterMetaTypeStreamOperators<CustomStructure>("CustomStructure");
The latter requires stream operators to be defined for serialising content of the type.
QDataStream &operator<<(QDataStream &out, const CustomStructure &obj)
{
out << obj.A << obj.B;
return out;
}
QDataStream &operator>>(QDataStream &in, CustomStructure &obj)
{
in >> obj.A >> obj.B;
return in;
}
Now it's possible to save CustomStructure into QSettings
QVariant var = settings.value("custom");
if (var.isValid()) {
CustomStructure contact = var.value<CustomStructure>();
qDebug() << contact.A << contact.B;
} else {
CustomStructure contact = {"10", "20"};
settings.setValue("custom", qVariantFromValue(contact));
}