首页 > 解决方案 > 将具有已知 QMetaType::Type 的 QByteArray 反序列化为 QVariant

问题描述

我有一个QByteArray包含变量的原始数据。描述变量是已知的
QMetaType::Type

我想将此变量反序列化为QVariant

使用以下输入:

QByteArray bytes; // Consider it initialized
QMetaType::Type type; // Same

到目前为止,我的尝试不起作用:

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)

我无法更改我的输入或输出类型:

例子 :

//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)

标签: c++qt

解决方案


面对同样的问题,我使用提供的类型 id直接通过它的方法构建了QVariantfrom a :QByteArraydata()

QByteArray bytes; // Consider it initialized
QMetaType::Type type; // Same
QVariant result(type.id(),bytes.data());

如果构造失败,你最终会得到一个 invalid QVariant,但到目前为止,对于我的类型,它运行良好。


推荐阅读