I have a QByteArray containing the raw data of a variable.
The QMetaType::Type describing the variable is known.
I want to deserialize this variable into a QVariant
With the following inputs :
QByteArray bytes; // Consider it initialized
QMetaType::Type type; // Same
My attempts so far do not work:
QVariant var{bytes};
var.convert(type); // Does not work, apparently QVariant expects bytes to be a string representation of the variable
QDataStream ds(bytes, QIODevice::ReadOnly);
QVariant var;
ds >> var; // Does not work because bytes does not come from the serialization of a QVariant (especially, it lacks type information)
I cannot change my inputs or output types :
- The inputs must be of type
QByteArrayandQMetaType::Type. - The output must be of type
QVariant
Example :
//Inputs
QByteArray bytes = { 0x12, 0x34, 0x56, 0x78 };
QMetaType::Type type = QMetaType::UInt; // Suppose the size of unsigned int is 4 bytes (could be 2)
// Note: this is an example, in pratice I have to manage many types, including double
//Expected output:
QVariant var = deserialize(bytes, type);
// var.type() == QMetaType::UInt
// var.toUInt() == 305419896 (== 0x12345678)