QVariant with custom class pointer does not return same address

假如想象 提交于 2019-12-04 09:40:10

This works for me using Qt 5.9:

#include <QVariant>
#include <QDebug>

class CustomClass
{
public:
    CustomClass()
    {
    }
};    
Q_DECLARE_METATYPE(CustomClass*)

class OtherClass
{
public:
    OtherClass()
    {
    }
};
Q_DECLARE_METATYPE(OtherClass*)

int main()
{
    CustomClass *c = new CustomClass;
    OtherClass *o = new OtherClass;
    QVariant v;
    v.setValue(c);
    QVariant v2;
    v2.setValue(o);

    qDebug() << v.userType() << qMetaTypeId<CustomClass*>() << v2.userType() << qMetaTypeId<OtherClass*>();
    qDebug() << v.value<CustomClass*>() << c << v2.value<OtherClass*>() << o;

    return 0;
}

And the output i got:

1024 1024 1025 1025
0x81fca50 0x81fca50 0x81fca60 0x81fca60

As @thuga mentioned in the comments, you need to use void* and static_cast along with QVariant::fromValue.

#include <QCoreApplication>
#include <QDebug>
#include <QMetaType>

class TestClass
{
public: TestClass() { qDebug() << "TestClass()::TestClass()"; }
};

Q_DECLARE_METATYPE(TestClass*)

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    qDebug() << "metaTypeId =" << qMetaTypeId<TestClass*>();

    auto testObject = new TestClass;
    QVariant variant(QVariant::fromValue(static_cast<void*>(testObject)));
    auto test = static_cast<TestClass*>(variant.value<void*>());

    qDebug() << testObject << variant << test;

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