我有一个包含变量原始数据的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 variableQDataStream 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)我不能更改输入或输出类型:
输入必须是QMetaType::Type.
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)发布于 2021-01-18 13:51:16
面对同样的问题,我使用提供的类型id直接通过QByteArray的data()方法从QByteArray构建data():
QByteArray bytes; // Consider it initialized
QMetaType::Type type; // Same
QVariant result(type.id(),bytes.data());如果构造失败,您将得到一个无效的QVariant,但到目前为止,对于我的类型,它工作得很好。
发布于 2020-08-07 10:56:26
您可以将其写入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(); //305419896https://stackoverflow.com/questions/63299770
复制相似问题