QJSEngine: Q_INVOKABLE method that returns pointer to subclass of QObject
-
Suppose I have some class that derives from QObject:
class MyTest : public QObject { Q_OBJECT // ... };
And I want to return pointer to this class from some
Q_INVOKABLE
method, like this:Q_INVOKABLE MyTest *createMyTest(){ return new MyTest(); }
However, when I try to invoke this method from the script in
QJSEngine
, I get the following error:Error: Unknown method return type: MyTest*
If I make
createMyTest()
to returnQObject*
instead ofMyTest*
, it works. But of course this would force me to use casts, which I'd like to avoid. So, how to make it work withMyTest*
?
Just by chance, I tried to declare metatype, as follows:Q_DECLARE_METATYPE(MyTest*)
But this didn't help.
Thanks in advance. -
@Leonardo, thank you, that works.
I'm still confused by the QML and
QJSEngine
interrelation. Like, how large part of QML should I learn in order just to useQJSEngine
.And, for example, how to use qml's
import
in JavaScript (not QML) code? Say, if I register instantiable type like this:qmlRegisterType<MyTest>("com.mycompany.myclasses", 1, 0, "MyTest");
Does that mean that I should import
com.mycompany.myclasses
somehow, in order for things to work correctly?QJSEngine
documentation doesn't contain things related to this. -
Hi. I'm not sure I understand what you mean, but take a look here:
http://doc.qt.io/qt-5/qtqml-javascript-imports.html#imports-within-javascript-resources
It might help.