Qml variant to custom QtObject
-
I have 2 different C++ objects using Q_PROPERTY and Q_INVOKABLE for a function, in my qml file I have this:
@
include MyObject 1.0 //from c++
incluce MyInvokable 1.0 //from c++property variant myVariant
MyObject{
id:myObject
}MyInvokable{
id: myInvokable
}
onCallFunction:{
myVariant = myObject;
myInvocable.invokableFunction( myVariant )
}@At MyInvokable function I can't get the value of MyObject:
@
void MyInvocable::invocableFunction(QVariant variant)
{
MyObject myObject = qvariant_cast<MyObject>(variant) ; //cant convert to MyObject
qDebug() << "foo: " << myObject.foo();
}
@MyObject has the macro
@Q_DECLARE_METATYPE(MyObject);@How can I convert QVariant to my custom Object ?
Regards
-
You don't need to convert from QVariant, try to work with QObject* pointers.
@
void MyInvocable::invocableFunction(QObject* object)
{
MyObject* myObject = static_cast<MyObject*>(object);
qDebug() << "foo: " << myObject->foo(); // pointers!
}
@ -
I agree with beemaster, just that I would replace that static_cast with a much more safe qobject_cast.
-
Reading your qml, you use a variant there too. Its almost never useful to have a variant in QML, since QML is typesafe. In this case you don't need that property in the first place, but otherwise you should consider using the QtObject type instead;
-
Thanks beemaster, Thomas Zander I have taken your advices and now my program works.