Serialisation of user-defined data in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

Overview[edit | edit source]

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

Description[edit | edit source]

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

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

Solution[edit | edit source]

Let's assume that 76ytuiytuityutyutututyutyutyu 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();