Convert QPair to QVariant

空扰寡人 提交于 2019-12-05 03:49:59

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;

    // ...
}

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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!