开发者

QMap Serialization in Qt

开发者 https://www.devze.com 2023-02-18 01:10 出处:网络
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 t

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消