PDA

View Full Version : how QDataStream and QByteArray related



dognzhe
7th May 2009, 05:53
I am not sure why every one has to use QDataStream with QByteArray ??
why???

please have a look the code


QBuffer buffer;
QImageWriter writer(&buffer, "PNG");
writer.write( randomImage() );
QByteArray data;
QDataStream stream( &data, QIODevice::WriteOnly );
stream << (quint32)buffer.data().size();
data.append( buffer.data() );
socket.write( data );

this code is to send a picture.
for same purpose:


QBuffer buffer;
QImageWriter writer(&buffer, "PNG");
writer.write( randomImage() );
QByteArray data;
QDataStream stream(&socket);
stream << (quint32)buffer.data().size();
stream << buffer.data();

works good as well.

1 i am so confused, what is purpose of having QByteArray in first code???

2 and in second code i don't even need socket.write( ) to send data... why>?

3 in first code, dose "stream << (quint32)buffer.data().size();" means write the size into (QByteArray) data?

spirit
7th May 2009, 06:01
QByteArray is a container for a raw data.

faldzip
7th May 2009, 08:45
I think the reason for use QByteArray could be here (Qt Docs for QIODevice::write()):

Writes the content of byteArray to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.
so you can store your raw data, then TRY ti write it with write() function, and if it fails or wrote not all data, you already have raw data to resolve that problem. So i think it's good to check how many bytes write() did actualy write, and maybe try to write the missing data, which is easy when you have them stored as QByteArray.