Important: Please read the Qt Code of Conduct -

QJSEngine: Q_INVOKABLE method that returns pointer to subclass of QObject

  • Suppose I have some class that derives from QObject:

    class MyTest : public QObject {
       // ... 

    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:


    But this didn't help.
    Thanks in advance.

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


  • @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:

    It might help.