开发者

QDataStream Serialization Problem

Here goes my Code first.

QByteArray buff;
QDataStream stream(&buff, QIODevice::ReadWrite);
stream.setVersion(QDataStream::Qt_4_7);
stream << 5;
stream << 6;
qDebug() << buff;
int x;
int y;
stream >> x >> y开发者_StackOverflow社区;
qDebug() << x << y;

I expect x be 5 and y be 6. But its showing 0 0 Here is the output

"
0 0


As Frank mentioned the QDataStream is still at the end position (after writing your data). If you don't want to create a new stream, it should also be possible to call stream.reset() to put the stream's internal position to the beginning. Or something like stream.seek(0).


Try this:

QByteArray buff;
QDataStream stream(&buff, QIODevice::ReadWrite);
stream.setVersion(QDataStream::Qt_4_0);
stream << 5;
stream << 6;
qDebug() << buff.toHex();

int x;
int y;

// This line will move the internal QBuffer to position 0
stream.device()->reset();

stream >> x >> y;
qDebug() << x << y;

Output:

"0000000500000006" 
5 6 


You can't read/write like this from/to a QByteArray using a single QDataStream, at the same time, due to the data stream's internal state (stream position). Try with a second QDataStream for reading.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜