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 return QObject* instead of MyTest*, it works. But of course this would force me to use casts, which I'd like to avoid. So, how to make it work with MyTest*?
    Just by chance, I tried to declare metatype, as follows:

    Q_DECLARE_METATYPE(MyTest*)
    

    But this didn't help.
    Thanks in advance.



  • You need to register your subclass to have it available in qml.

    qmlRegisterType<MyTest>();


  • @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 use QJSEngine.

    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.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.