Problem getting C++ class exposed to QML
-
I have the following C++ classes:
@class Bar : public QObject
{
...
};class Foo : public QObject
{
Q_PROPERTY(Bar* bar READ bar)
...
};@I add an instance of Foo to my the QML context, but when I run it I get this error:
@QMetaProperty::read: Unable to handle unregistered datatype 'Bar*' for property 'Foo::bar'@
Since both Foo and Bar are QObject subclasses, I thought that QML could use them without needing to go through the Q_DECLARE_METATYPE or qRegisterMetaType process. Am I mistaken? -
Hi,
In this case it looks like it is the meta type system that is having problems -- from C++ does calling foo->property("bar") give the same error?
From a QML perspective it should work fine with the following (from memory):
@
Q_PROPERTY(QObject* bar READ bar)
@Alternatively you will need to register the types.
Regards,
Michael -
mbrasser.
Thank you.
that @Q_PROPERTY(QObject* bar READ bar)@Worked fine for me.
-
But how do we register Bar so that we don't need to expose it as a QObject? It IS a Bar after all. I'm having the same issues. I can't get QML to see my types, even though I have:
in main.cpp
@qmlRegisterType<StructuralElement>();@in my element:
@Q_PROPERTY(StructuralElement* parent READ Parent WRITE Reparent NOTIFY ParentChanged)@I still get:
QMetaProperty::read: Unable to handle unregistered datatype 'StructuralElement*' -
[quote author="gemmell" date="1394964951"]
I still get:
QMetaProperty::read: Unable to handle unregistered datatype 'StructuralElement*'
[/quote]Hi,
I think you forgot add macros:
@
Q_DECLARE_METATYPE(StructuralElement)
@In you case it's can looks like:
@
class Bar : public QObject
{
...
};
Q_DECLARE_METATYPE(Bar)class Foo : public QObject
{
Q_PROPERTY(Bar* bar READ bar)
...
};
Q_DECLARE_METATYPE(Foo)
@For more information please read this "doc":http://qt-project.org/doc/qt-5/qmetatype.html and "this":http://qt-project.org/doc/qt-5/qmetatype.html#Q_DECLARE_METATYPE.
Also in your main file or <project>_plugin.cpp (if you create a QtQuick plugin) you must add:
@
qmlRegisterType<Foo>(uri, 1, 0, "Foo");
qmlRegisterType<Bar>(uri, 1, 0, "Bar");
@ -
I have done
@Q_DECLARE_METATYPE(Model::StructuralElement*)@I can't do
@Q_DECLARE_METATYPE(Model::StructuralElement)@because it's an abstract class...
@1>c:\qt\qt5.2.1\5.2.1\msvc2012_64\include\qtcore\qmetatype.h(719): error C2259: 'Model::StructuralElement' : cannot instantiate abstract class @
I never pass a StructuralElement through (obviously, it's abstract!), I return a pointer to one of these from a Q_PROPERTY like so:
@Q_PROPERTY(StructuralElement* parent READ Parent WRITE Reparent NOTIFY ParentChanged)@I can use that property no problems in C++, but I can't call it from QML or I get the print out mentioned above. Perhaps I am supposed to do this instead:
@qmlRegisterType<StructuralElement*>() @
Nope, that doesn't compile. How's it supposed to work?