Important: Please read the Qt Code of Conduct -

Return QObject * objects to be used both in QML and Javascript

  • Hi,

    I am a little bit confused.

    I have a JSWrapperObject inheriting from QObject with a test method. This method must return (in some way) a QObject * to the JS engine and the QML engine depending on who called it. What type should I return precisely and how should I add it to the engines?

    For the moment:

    • Returning a QJsonObject works but is useless for me as I need to call methods on the returned object;
    • Returning a QJSValue wrapping my object works in the JS engine but not in the QML engine;
    • doing qmlEngine->rootContext()->setContextProperty("test", new JSWrapperObject); works in QML, but not in JS.

    Ultimately, I would like the GUI (QML) to call JS methods which in turn call my C++ methods.

    Thanks for your help.

  • Some updates. I did some tests. So:

    • Returning a QVariant object to QML engine works;
    • Returning my custom C++ object to QML does NOT work. The type is correctly registered because I can do something like:
      qmlEngine->rootContext()->setContextProperty("testObj", new namespace::JSWrapperObject());

    I can access testObj and check that the type is correctly registered.

    Any idea why I could use this type by creating it directly from C++ into QML with the previous line but not by returning it from Q_INVOKABLE methods?

Log in to reply