QVariant with custom class pointer does not return same address

只谈情不闲聊 提交于 2019-12-14 03:42:07

问题


I need to assign a pointer to a custom class in qml using QQmlContext::setContextProperty(). Another qml object has Q_PROPERTY of the same type to retrieve it again.

A simple test showed me that the conversion does not work like i thought.

#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(qMetaTypeId<TestClass*>(), testObject);
    auto test = variant.value<TestClass*>();

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

    return 0;
}

This tiny test application gives me an output like this:

metaTypeId = 1024
TestClass::TestClass()
0x1b801e0 QVariant(TestClass*, ) 0x0

I would really like to get the same pointer out again after converting it down to a QVariant. Later I will assign it to a qml context and then the conversation must work correctly.


回答1:


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



回答2:


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;
}


来源:https://stackoverflow.com/questions/44501171/qvariant-with-custom-class-pointer-does-not-return-same-address

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