October 3, 2011

p-himik p-himik
Lab Rat
263 posts

QDataStream and QByteArray as a buffer

 

Can you explain why this code:

  1. int main(int argc, char *argv[])
  2. {
  3.     QByteArray buffer;
  4.     QHash< QString, QByteArray > data;
  5.     data.insert( "123", "qwe" );
  6.     qDebug() << "Data:" << data;
  7.     QDataStream stream( &buffer, QIODevice::ReadWrite );
  8.     stream << data;
  9.     qDebug() << "Buffer's size:" << buffer.size();
  10.     data.clear();
  11.     stream >> data;
  12.     qDebug() << "Data:" << data;
  13.     qDebug() << "Buffer's size:" << buffer.size();
  14.     qDebug() << "Buffer:" << buffer.toHex();
  15. }

gives this output:
  1. Data: QHash(("123", "qwe"))
  2. Buffer's size: 21
  3. Data: QHash()
  4. Buffer's size: 21
  5. Buffer: "000000010000000600310032003300000003717765"

As i can understand from http://doc.qt.nokia.com/stable/datastreamformat.html streaming from data to buffer is correct (the last line of the output). But why then there is no streaming from buffer to data?

4 replies

October 3, 2011

p-himik p-himik
Lab Rat
263 posts

Stream’s status becomes QDataStream::ReadPastEnd so i think i just misunderstood logic of streaming.

October 3, 2011

peppe peppe
Ant Farmer
1028 posts

Indeed. You have to seek() back to the beginning of the buffer.

 Signature 

Software Engineer
KDAB (UK) Ltd., a KDAB Group company

October 3, 2011

p-himik p-himik
Lab Rat
263 posts

Do you mean QDataStream::device().seek()?

October 3, 2011

peppe peppe
Ant Farmer
1028 posts

Yes (remember that QByteArray isn’t a QIODevice, thus QDataStream creates a QBuffer internally).

 Signature 

Software Engineer
KDAB (UK) Ltd., a KDAB Group company

 
  ‹‹ QThread::terminate doesn’t work      Changing state of QStateMachine based on a signal argument. ››

You must log in to post a reply. Not a member yet? Register here!