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?
Asked
Active
Viewed 8,893 times
13

arc_lupus
- 3,942
- 5
- 45
- 81
-
1You could use QStringList instead of QPair to host the two integers. QStringList can be converted to QVariant. – user2672165 Dec 13 '14 at 17:26
-
Ok, that's a simple solution, I should have known that for myself -> head -> desk... – arc_lupus Dec 13 '14 at 17:28
-
3Yiiikes @ _string_ list for an _integer_ pair! – László Papp Dec 14 '14 at 06:53
-
@arc_lupus any chance you mark this as resolved ? – azf Dec 16 '14 at 18:58
-
@totem: Thanks for remembering me! – arc_lupus Dec 16 '14 at 19:48
2 Answers
24
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;
// ...
}

azf
- 2,179
- 16
- 22
-
I completely missed the `value
()` in the `QVariant`'s documentation since I am actually using a pair to deliver some `QAction` data. Your post is much appreciated. +1 – rbaleksandar Mar 14 '16 at 20:31 -
According to the QMetaType docs some types are automatically registered and don't need this macro: http://doc.qt.io/qt-5/qmetatype.html#Type-enum including QPair
– Tom Sep 21 '18 at 10:16
4
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;
}

Antonio Dias
- 2,751
- 20
- 40