Convert QPair to QVariant

I have the following problem: I want to transfer data via TCP and write a function for this. For maximum reuse, the function template f(QPair<QString, QVariant> data) . The first value (aka QString ) is used by the recipient as the destination address, the second contains data. Now I want to pass the value of QPair<int, int> , but, unfortunately, I can not convert QPair to QVariant . It would be optimal to be able to transfer a couple of int values โ€‹โ€‹without having to write a new function (or overload the old one). What is the best alternative for QPair in this case?

+5
source share
2 answers

You must use the special Q_DECLARE_METATYPE() macro to create custom types for QVariant . Please read the document carefully to understand how this works.

For QPair, although it's pretty simple:

 #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; // ... } 
+12
source

Note: this answer uses other functions to convert them, which you may consider.

You can use QDataStream to serialize QPair to QByteArray , and then convert it to QVariant , and you can reverse process to get QPair from 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; } 
+2
source

Source: https://habr.com/ru/post/1208959/


All Articles