问题描述
我有以下问题:我想通过TCP传输数据,并为此编写了一个函数.为了获得最大的可重用性,功能模板为f(QPair<QString, QVariant> data)
.接收器将第一个值(也称为QString
)用作目标地址,第二个值包含数据.现在我想传输一个QPair<int, int>
值,但是不幸的是我无法将QPair
转换为QVariant
.最佳方法是能够传输一对int
值而不必编写新函数(或使旧函数过载).在这种情况下,QPair
的最佳替代方法是什么?
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?
推荐答案
您必须使用特殊的宏Q_DECLARE_METATYPE()
使自定义类型可用于QVariant
系统.请仔细阅读文档以了解其工作原理.
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.
对于QPair而言,它非常简单:
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;
// ...
}
这篇关于转换QPair到QVariant的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!