Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Saving custom structures and classes to QSettings

From Wiki
Jump to: navigation, search
Article Metadata
Compatibility
Platform(s):
Symbian
Article
Created: divanov (11 Oct 2010)
Last edited: hamishwillee (11 Oct 2012)

Overview

Custom types registered using qRegisterMetaType() and qRegisterMetaTypeStreamOperators() can be stored using QSettings.

Detailed description

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));
}
This page was last modified on 11 October 2012, at 01:18.
105 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×