Serializing QVariant through QDataStream

Lex picture Lex · Oct 23, 2013 · Viewed 7.8k times · Source

I'm possibly writing it wrong but here's the code that i'm trying to execute and it fails to do what's 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 documentation of the QVariant class :

http://qt-project.org/doc/qt-5.1/qtcore/qvariant.html#type

It should serialize the value 123 correctly to the QByteArray but doesn't do so,instead it just writes out:

test: 

Anybody has an idea how to fix this ?

EDIT

Well, maybe it was not clear but here is the original problem:

I have possibly any QVariant built-in type stored in the QVariant such as QStringList, QString , double, int , etc....

What I want is a way to serialize the QVariant to a string and restoring it without having to do it myself 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 was thinking that passing by a QDataStream could pass me a serialized version of the QVariant.

EDIT 2

Thanks to the answer of piotruś I was able to answer my problem. Here's 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;
}

Answer

Dan Milburn picture Dan Milburn · Oct 23, 2013

QDataStream does not write text, it writes binary data in the form specified here. So you should not expect to see any printable characters in the byte array, and certainly not the string representation of the number.

QTextStream is used for writing out text, however it is not directly compatible with QVariant. You would need to write your own code to test what type the variant contains and write out the appropriate string.