Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QVariant with custom class pointer does not return same address

Tags:

qt

qt5

qvariant

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.

like image 874
feedc0de Avatar asked Jun 12 '17 13:06

feedc0de


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 output i got:

1024 1024 1025 1025
0x81fca50 0x81fca50 0x81fca60 0x81fca60
like image 73
thuga Avatar answered Oct 22 '22 21:10

thuga


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;
}
like image 5
Silas Parker Avatar answered Oct 22 '22 23:10

Silas Parker