2
votes

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;
qDebug() << x << y;

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

"
0 0
3

3 Answers

4
votes

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).

1
votes

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 
0
votes

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.