QVariant streaming from QDataStream
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:
Code:
#include <QVariant>
#include <QDataStream>
#include <QString>
#include <QStringList>
#include <QFile>
int main(int argc, char *argv[])
{
QVariant v
(123);
// The variant now contains int x = v.toInt(); // x = 123
qDebug("x=%#x", x); // prints x
// 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
Re: QVariant streaming from QDataStream
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).
Re: QVariant streaming from QDataStream
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
Re: QVariant streaming from QDataStream
std::ifstream might be an option as well.