I have a 2 classes: valueNode
and 开发者_Python百科keyNode
. Both of these classes have 2 private members. Now I create a QMap< keyNode , valueNode >
. for this I override operator<()
. I want to serialize this QMap but I don't know how.
QMap<QString, QString> map;
map.insert("Hello", " World!");
QByteArray data;
QDataStream * stream = new QDataStream(&data, QIODevice::WriteOnly);
(*stream) << map;
delete stream;
// Now QByteArray should have the map as serialized data.
This should work.
You might wonder about the new and delete madness, but there is a reason: there is no way to flush the data from the stream to the bytearray, except by deconstructing the stream. Or maybe there is, give me a comment if I'm wrong.
Edit:
Oh yeah, forgot one thing.
You need to make these functions:
QDataStream & operator << (QDataStream & out, const MyClass & object);
QDataStream & operator >> (QDataStream & in, MyClass & object);
Introduce them in the headers of your classes and implement in the cpp file of that class.
// MyClass.h
MyClass
{
...
};
QDataStream & operator << ...
QDataStream & operator >> ...
Note that it must be a global function and not a member function.
Note that you must create a pair for each of your classes.
Store it in a QVariant which you can then use a QDataStream to read/write it.
精彩评论