c++ - 将具有已知 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)
我无法更改我的输入或输出类型:
- 输入必须
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)
解决方案
面对同样的问题,我使用提供的类型 id直接通过它的方法构建了QVariant
from a :QByteArray
data()
QByteArray bytes; // Consider it initialized
QMetaType::Type type; // Same
QVariant result(type.id(),bytes.data());
如果构造失败,你最终会得到一个 invalid QVariant
,但到目前为止,对于我的类型,它运行良好。
推荐阅读
- php - 旧主题上的 PHP 7 错误 - Prestashop 1.6 / Thirtybees:'不能将字符串偏移量用作数组'
- swift - 自定义集合视图单元格大小
- spartacus-storefront - 如何在 spartacus 中自定义/扩展 ootb 组件
- ada - 如何在 Ada 中使用错误代码退出主程序?
- python - 屏蔽和修改来自 FPGA 串行通信的 8 字节信号
- node.js - 您能否定义“page_objects_path”目录,该目录将从所有子文件夹中读取而无需明确指定它们?
- python - 当我将单个记录删除到模板中时,所有记录都被删除
- docker - “ERRO [0002] 错误等待容器:上下文已取消” sshfs 插件问题
- python - 管道后将pymongo查询从字符串转换为双精度
- android - Android Studio Recyclerview (horizontal) - 离开视图时移除动画