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.

Serialisation of user-defined data in Qt

From Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): All (S60)
Compatibility
Platform(s): S60 3rd Edition, FP1
S60 3rd Edition, FP2
S60 5th Edition
Symbian
S60 5th Edition
S60 3rd Edition FP2
S60 3rd Edition FP1
Article
Keywords: QDataStream
Created: User:Kbwiki (27 Jan 2010)
Last edited: hamishwillee (11 Oct 2012)

Overview

This article describes how to provide a serialisation of user-defined custom classes in Qt.

Description

To serialise our own custom Qt classes, we need to write appropriate stream operators:

 QDataStream &operator<<(QDataStream &, const MyClass &);
QDataStream &operator>>(QDataStream &, MyClass &);

Solution

Let's assume that MyClass is a user-defined class.

 class MyClass
{
public:
int m_int;
QString m_str;
};

Writing into streams - Externalisation:

 QDataStream &operator<<(QDataStream &s, const MyClass& myClass)
{
//Extracting from the stream
int i = myClass.m_int;
QString str = myClass.m_str;
s<<i;
s<<str;
return s;
}

Reading from the stream - Internalisation:

 QDataStream &operator>>(QDataStream& s, MyClass& myClass)
{
s>>myClass.m_int;
s>>myClass.m_str;
return s;
}

Serialisation - Writing contents of the class into file:

 MyClass mClass;
mClass.m_int = 100;
mClass.m_str = "String sting";
QString location = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
location += "/customDataStream.txt";
QFile file;
file.setFileName(location);
bool err = file.open(QIODevice::WriteOnly);
QDataStream out(&file);
out<<mClass;
file.close();

Serialisation - Reading into user-defined class from file:

 MyClass mClass;
QString location = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
location += "/customDataStream.txt";
QFile file(location);
bool err = file.open(QIODevice::ReadOnly);
QDataStream in(&file);
in>>mClass;
int i = mClass.m_int;
QString str = mClass.m_str;
file.close();
This page was last modified on 11 October 2012, at 01:18.
69 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.

×