Maybe I am writing this incorrectly, but here is the code that I am trying to execute and it does not work to do what was expected:
#include <QDataStream> #include <QByteArray> #include <QVariant> #include <iostream> int main(){ QByteArray data; QDataStream ds(&data,QIODevice::WriteOnly); QVariant v(123); ds << v; std::cout <<"test: " << data.data() << std::endl; // "test: 123" return 0; }
Given the example in the QVariant class documentation:
http://qt-project.org/doc/qt-5.1/qtcore/qvariant.html#type
It should correctly serialize the value 123 in a QByteArray, but does not do this, instead, it simply writes:
test:
Anyone have an idea how to fix this?
EDIT
Well, maybe it was not clear, but here is the original problem:
I have any built-in QVariant type stored in QVariant such as QStringList, QString, double, int, etc.
What I want is a way to serialize QVariant into a string and restore it without having to do it on my own for each type. As far as I know, the QVariant :: toString () method does not work with all types that are accepted through QVariant, and I thought that passing a QDataStream could pass me a serialized version of QVariant.
EDIT 2
Thanks to piotruΕ's answer, I was able to answer my problem. Here is the program:
int main(){ QString str; { //serialization QByteArray data; QDataStream ds(&data,QIODevice::WriteOnly); QVariant v(123); ds << v; data = data.toBase64(); str = QString(data); cout << str.toStdString() << endl; } { //deserialization QByteArray data = str.toLatin1(); data = QByteArray::fromBase64(data); QDataStream ds(&data,QIODevice::ReadOnly); QVariant v; ds >> v; cout << v.toInt() << endl; } return 0; }