PDA

View Full Version : Serialization



donmorr
15th November 2006, 21:19
Hello All,

Is it possible to serialize instances of my own classes so I can store them on disk? These classes contain STL types such as string & vector<string>. Would I be better off using QString and QStringList types if I was to serialize them?

Cheers,
Donal

jpn
16th November 2006, 07:58
Sounds like a job for QDataStream. Pay attention to the Detailed Description.

donmorr
16th November 2006, 13:26
Hi,
Cheers for the reply.

I've had a look at QDataStream.
But that ony seems to support native types (int, char, etc)

How can u use it to store something like a QString or an instance of my own class?

Cheers

jpn
16th November 2006, 13:48
I told you to pay attention to the detailed description.. :)


Each item written to the stream is written in a predefined binary format that varies depending on the item's type. Supported Qt types include QBrush, QColor, QDateTime, QFont, QPixmap, QString, QVariant and many others. For the complete list of all Qt types supporting data streaming see the Format of the QDataStream operators (http://doc.trolltech.com/4.2/datastreamformat.html).


You can write QDataStream operators for your class:


QDataStream& operator << (QDataStream& stream, const SomeClass& some)
{
stream << ...
return stream;
}

QDataStream& operator >> (QDataStream& stream, SomeClass& some)
{
...
stream >> ..
return stream;
}

nouknouk
16th November 2006, 13:51
Overloaded operators << and >> for other data types are defined in the data class itself, not in the QDataStream class. This is better for the extensibility of the QDataStream class (in other words, you don't need to modify the QDataStream class itself to extend its supported types).

That means you have to look in each class you want to serialize if the functions like that exist :

QDataStream & operator<< ( QDataStream & stream, const QString & string ) (http://doc.trolltech.com/4.2/qstring.html#operator-lt-lt-62)
QDataStream & operator>> ( QDataStream & stream, QString & string )

EDIT: In addition, this url (http://doc.trolltech.com/4.2/datastreamformat.html) shows you all data serializable with QDataStream, given the Qt framework.

For you own needs, you will probably define you own overloaded operators for you specific data class.