QVariant serialization via QDataStream

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; } 
+6
source share
2 answers

QDataStream does not write text, it writes binary data in the form here . Therefore, you should not expect to see any printed characters in an array of bytes and, of course, not a string representation of a number.

QTextStream used to write text, however it cannot be directly compatible with QVariant . You will need to write your own code to check which type this option contains and write the appropriate line.

+4
source
 QByteArray data; QDataStream dsw(&data,QIODevice::WriteOnly); QVariant v(123); dsw << v; QDataStream dsr(&data,QIODevice::ReadOnly); QVariant qv; dsr>>qv; qDebug()<<qv.toString(); 

However, your data 123 have been recorded in QByteArray . A QByteArray point stored as a char array in memory will not show you β€œ123” if you try to debug this, but show β€œ{”, and this is ASCII code 123. You can still print this QByteArray from raw memory. You will do it as follows:

 const char *dataPtr = data.operator const char *(); int i=0; while (i<9) { std::cout << "[" << *dataPtr << "]"; ++dataPtr; ++i; } 

and output: [] [] [] [] [] [] [] [] [ { ]

you may want to do

 data.setByteOrder( QDataStream::LittleEndian ); 

to print bytes from a stream stored in a small trailing order.

+3
source

Source: https://habr.com/ru/post/956539/