Convert QPair to QVariant

arc_lupus picture arc_lupus · Dec 13, 2014 · Viewed 7k times · Source

I have the following problem: I want to transmitt data via TCP, and wrote a function for that. For maximum reusability the function template is f(QPair<QString, QVariant> data). The first value (aka QString) is used by the receiver as target address, the second contains the data. Now I want to transfer a QPair<int, int>-value, but unfortunately I can not convert a QPair to a 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). What is the best alternative for QPair in this case?

Answer

azf picture azf · Dec 13, 2014

You have to use the special macro Q_DECLARE_METATYPE() to make custom types available to QVariant system. Please read the doc carefully to understand how it works.

For QPair though it's quite straightforward:

#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;

    // ...
}