【发布时间】:2020-08-07 10:17:08
【问题描述】:
我有一个包含变量原始数据的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)
我无法更改我的输入或输出类型:
- 输入必须为
QByteArray和QMetaType::Type类型。 - 输出必须是
QVariant类型
例子:
//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)
【问题讨论】:
-
你为什么不干脆这样做:
auto v = QVariant(bytes.toUInt());? -
因为
unsigned int不会是我收到的唯一类型,这只是一个示例。我想避免单独管理每种类型。 -
您找到可行的解决方案了吗?