Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q_INVOKABLE method returning custom C++ type

Tags:

c++

qt

qml

I have a C++ method made Q_INVOKABLE. I can call this method from QML and it works when it returns basic types (like QString). But I can't with a custom type. How should I do this? Should I return a QVariant instead? Ideally, I would like to return a pointer to my custom type if possible.

EDIT I do:

qmlRegisterType<MyType>("Mine", 1, 0, "MyType");
qmlEngine->rootContext()->setContextProperty("testObj", new MyType());

I can use testObj global object or create MyType QML component. But I cannot use it in some javascript code as a return type from a Q_INVOKABLE C++ method.

like image 837
Korchkidu Avatar asked Jun 25 '14 17:06

Korchkidu


1 Answers

Note that the target of this answer are people with a similar problem, rather than the original asker.

The described method should work, at least in recent versions of Qt (I'm using Qt 5.12, but it should work in older versions too). Maybe it was a bug in one of the first QML releases.

Checklist: Verify you have done the following:

  • Registered your type qmlRegisterType<MyType>("Mine", 1, 0, "MyType"); (or use qmlRegisterUncreatableType)
  • Imported your custom types in qml: import Mine 1.0
  • Derived your class from QObject.
  • Added Q_OBJECT to your class definition.

When returning pointers from a Q_INVOKABLE method, please take object ownership into account.

like image 158
m7913d Avatar answered Sep 29 '22 19:09

m7913d