QVariant with a custom class pointer does not return the same address

I need to assign a pointer to a native class in qml using QQmlContext::setContextProperty(). Another qml object is of Q_PROPERTYthe same type to get it again.

A simple test showed that the conversion did not work as 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 this output:

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

I would really like to get the same pointer again, converting it to QVariant. Later I will assign it to the qml context, and then the conversation should work correctly.

+4
source share
2 answers

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 result I got:

1024 1024 1025 1025
0x81fca50 0x81fca50 0x81fca60 0x81fca60
+4
source

@thuga, void* static_cast 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;
}
+2

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


All Articles