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?
Convert QPair to QVariant
9.4k views Asked by arc_lupus At
2
There are 2 answers
0
On
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
.
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;
}
You have to use the special macro
Q_DECLARE_METATYPE()
to make custom types available toQVariant
system. Please read the doc carefully to understand how it works.For QPair though it's quite straightforward: