[英]Deserializing QByteArray with known QMetaType::Type into 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)
我无法更改我的输入或 output 类型:
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 直接通过其data()
方法从QByteArray
构造QVariant
:
QByteArray bytes; // Consider it initialized
QMetaType::Type type; // Same
QVariant result(type.id(),bytes.data());
如果构造失败,你最终会得到一个无效的QVariant
,但到目前为止,对于我的类型,它运行良好。
您可以写入unsigned int
,然后将其转换为QVariant
:
const char data[] = { 0x12, 0x34, 0x56, 0x78 };
QByteArray bytes { QByteArray::fromRawData( data, 4) };
QDataStream s {&bytes, QIODevice::ReadOnly};
//write out the data to uint
unsigned int x{};
s >> x;
//create a Qvariant from it
QVariant var{x};
qDebug () << "x: " << x; //305419896
qDebug () << "variant: " << var; //QVariant(uint, 305419896)
qDebug () << "variant uint: " << var.toUInt(); //305419896
或者,您也可以直接构造QVariant
:
auto v = QVariant(bytes.toHex().toUInt());
//auto v = QVariant(bytes.toUInt()); //this will not work
qDebug () << "Bytes to uint; " << v.toUInt(); //305419896
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.