PDA

View Full Version : QVariant streaming from QDataStream



XCG
25th February 2008, 21:58
Hi
I'm using Qt 4.3.3 and trying to stream binary data (read from an arbitrary file). Therefore I started with an example as found in the Qt documentation just a few lines of code:


#include <QVariant>
#include <QDataStream>
#include <QString>
#include <QStringList>
#include <QFile>


int main(int argc, char *argv[])
{
QFile file("./test");
file.open(QIODevice::ReadOnly);

QVariant v(123); // The variant now contains
int x = v.toInt(); // x = 123

qDebug("x=%#x", x); // prints x

QDataStream in(&file);

// prints "Type is int"
qDebug("Type is %s, userType=%d", v.typeName(), v.userType());

in >> v; // *Should* reads an Int variant

int z = v.toInt(); // z = 0 !!!!
// Type is no longer Int variant:
qDebug("Type is %s, userType=%d", v.typeName(), v.userType());

int n;
in >> n; // Reads a normal int

qDebug("n=%#x", n); // this just works

return 1;
}

Here the few lines produce the following output:

markus@athlon:~/Test/bin> ./test
x=0x7b
Type is int, userType=2
QVariant::load: unable to load type 1061506118.
Type is (null), userType=1061506118
n=0x1010000
markus@athlon:~/Test/bin>

So it looks like the QVariant type is lost somehow during the call to the operator>>. Does anybody have an idea why the type has suddenly the value 1061506118 instead of 2?


Best regards, Markus

wysota
25th February 2008, 22:28
Are you aware of the fact that QDataStream is a serialization mechanism and not a general purpose binary stream? If you write an integer to the stream, you can't read a variant (and vice versa).

XCG
26th February 2008, 16:58
Hi
Thank you very much for your quick answer. Indeed I wasn't aware of this :o
Interestingly reading single characters out of a binary file worked for me with the streaming operator. But this is problably because then no endian conversion is needed.
Anyway, this means that both, QVariant's type and QVariant's value, are streamed to/from the file and I've to go with readRawData() to read a predefined binary format.

Best regards, Markus

wysota
26th February 2008, 17:12
std::ifstream might be an option as well.