[Qt-interest] how to achive the serialization in Qt

Andre Somers andre at familiesomers.nl
Tue Apr 13 15:38:40 CEST 2010


On 13-4-2010 15:07, Ramesh wrote:
>
> Hi,
>
> Folks, can you help me in how to achieve the serialization in Qt,
>
> I have some idea about QDataStream with this we can achieve the data 
> stream,
>
> In the documentation it is mentioned that we can write char, int, etc 
> the other  Data types, if I try to write the object it is throwing error L
>
> How to write the object to file using QDataStream?
>
>

It is unclear what you refer to if you talk about "the object". I'll 
assume it is an instance of a class you defined yourself. The easiest 
way to make the class serializable, is to implement QDataStream& 
operator<<(QDataStream& stream, const MyClass& class) and QDataStream& 
operator>>(QDataStream& stream, MyClass& class) as non-member functions 
of your class. Qt classes use the same method, according to the docs:


          Reading and writing other Qt classes.

    In addition to the overloaded stream operators documented here, any
    Qt classes that you might want to serialize to a QDataStream will
    have appropriate stream operators declared as non-member of the class:

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

    For example, here are the stream operators declared as non-members
    of the QImage <qimage.html> class:

      QDataStream&  operator<<  (QDataStream&  stream, const QImage&  image);
      QDataStream&  operator>>  (QDataStream&  stream, QImage&  image);

    To see if your favorite Qt class has similar stream operators
    defined, check the *Related Non-Members* section of the class's
    documentation page.



Inside your own definition, you can stream in/out all the member values 
that together represent your object's state. You can then feed in your 
own instances in a QDataStream like you would any other type.

Of course, there are other ways to achieve serialization, like writing 
to and reading from an XML file, or a database, or...

André

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100413/2469c948/attachment.html 


More information about the Qt-interest-old mailing list