PDA

View Full Version : Serialize myClass



^NyAw^
22nd October 2007, 18:52
Hi,

Actually I have a class that I implemented a "save" method to serialize my class.

Now I have created a QLinkedList<MyClass*>. How I have to do to save this list? I know that I can do something like this:


QDataStream ds;
...
ds << qMyLinkedList;


What really does this? Have I to reimplement any method?

Thanks,

DeepDiver
22nd October 2007, 19:15
As a general advise: use the debugger and walk through and you will see, what happens.
Or browse the source code - Qt is open source, though it's easy to see how things are implemented.

Back to your question:

template <typename T>
QDataStream& operator<<(QDataStream& s, const QList<T>& l)
{
s << quint32(l.size());
for (int i = 0; i < l.size(); ++i)
s << l.at(i);
return s;
}

This is the implementation of the operator you are talking about. (qdatastream.h:239 - Qt 4.3.2)
As you see the size of the list is written to the stream. Next all elements are written.
The elements need to implement the operator<< and operator >>.
Have all look at qdatetime.h and qdatetime.cpp how this looks like:


class QDate
...
friend Q_CORE_EXPORT QDataStream &operator<<(QDataStream &, const QDate &);
friend Q_CORE_EXPORT QDataStream &operator>>(QDataStream &, QDate &);


QDataStream &operator<<(QDataStream &out, const QDate &date)
{
return out << (quint32)(date.jd);
}

...

QDataStream &operator>>(QDataStream &in, QDate &date)
{
quint32 jd;
in >> jd;
date.jd = jd;
return in;
}

Good luck,

Tom

wysota
22nd October 2007, 19:24
Note that you are using POINTERS, so if you use the serialization mechanism of the list, you'll serialize pointers instead of objects, and that's surely not what you want. You have to either create a list of objects or do the serialization manually (for instance by subclassing QList<MyClass*> and reimplementing its stream operators in a fashion similar to what DeepDiver suggested).

^NyAw^
22nd October 2007, 19:32
Ok,

Thank you very much,

DeepDiver
23rd October 2007, 10:53
Note that you are using POINTERS, so if you use the serialization mechanism of the list, you'll serialize pointers instead of objects, and that's surely not what you want. You have to either create a list of objects or do the serialization manually (for instance by subclassing QList<MyClass*> and reimplementing its stream operators in a fashion similar to what DeepDiver suggested).

You are right! I didn't see NyAw declared a list of pointers. :o

^NyAw^
23rd October 2007, 11:27
Hi,
Thanks to you. I had wrote my code and works fine. I write "myList.count()" and then I do a "for" writing all the objects. The inverse process is done in open method.

Thanks,