简体   繁体   English

将QPair转换为QVariant

[英]Convert QPair to QVariant

I have the following problem: I want to transmitt data via TCP, and wrote a function for that. 我有以下问题:我想通过TCP传输数据,并为此编写了一个函数。 For maximum reusability the function template is f(QPair<QString, QVariant> data) . 为了获得最大的可重用性,函数模板为f(QPair<QString, QVariant> data) The first value (aka QString ) is used by the receiver as target address, the second contains the data. 第一个值(aka QString )由接收器用作目标地址,第二个值包含数据。 Now I want to transfer a QPair<int, int> -value, but unfortunately I can not convert a QPair to a QVariant . 现在我想转移一个QPair<int, int> ,但遗憾的是我无法将QPair转换为QVariant The optimum would be to be able to transfer a pair of int -values without having to write a new function (or to overload the old one). 最佳的方法是能够传输一对int而无需编写新函数(或使旧函数重载)。 What is the best alternative for QPair in this case? 在这种情况下, QPair的最佳替代方案是什么?

You have to use the special macro Q_DECLARE_METATYPE() to make custom types available to QVariant system. 您必须使用特殊宏Q_DECLARE_METATYPE()来使QVariant系统可以使用自定义类型。 Please read the doc carefully to understand how it works. 请仔细阅读文档以了解其工作原理。

For QPair though it's quite straightforward: 对于QPair,虽然它很简单:

#include <QPair>
#include <QDebug>

typedef QPair<int,int> MyType;    // typedef for your type
Q_DECLARE_METATYPE(MyType);       // makes your type available to QMetaType system

int main(int argc, char *argv[])
{
    // ...

    MyType pair_in(1,2);
    QVariant variant = QVariant::fromValue(pair_in);
    MyType pair_out = variant.value<MyType>();
    qDebug() << pair_out;

    // ...
}

Note: this answer uses another functions to convert them, something you may consider. 注意:这个答案使用其他函数来转换它们,您可以考虑使用它。

You could use QDataStream to serialize the QPair to QByteArray and then convert it to QVariant , and you can the inverse process to get the QPair from a QVariant . 您可以使用QDataStreamQPair序列化为QByteArray ,然后将其转换为QVariant ,您可以通过逆过程从QVariant获取QPair

Example: 例:

//Convert the QPair to QByteArray first and then
//convert it to QVariant
QVariant tovariant(const QPair<int, int> &value)
{
    QByteArray ba;
    QDataStream stream(&ba, QIODevice::WriteOnly);
    stream << value;
    return QVariant(ba);
}

//Convert the QVariant to QByteArray first and then
//convert it to QPair
QPair<int, int> topair(const QVariant &value)
{
    QPair<int, int> pair;
    QByteArray ba = value.toByteArray();
    QDataStream stream(&ba, QIODevice::ReadOnly);
    stream >> pair;
    return pair;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM