Is it valid to call QJSEngine::newQObject() in a C++ function called by a script?

352 views Asked by At

Consider this example:

ObjectCreator is set as global property via QJSEngine:

// ObjectCreator is exposed to engine_ env as global property
class ObjectCreator : public QObject
{
    Q_OBJECT

public:
    ObjectCreator(QJSEngine * engine, QObject * parent = nullptr) : QObject(parent), engine_(engine) {}
    
    // Called from script env
    Q_INVOKABLE QJSValue createObject();

private:
    
    // engine_ is not owned
    QJSEngine * engine_ = nullptr;
};

class SomeObj : public QObject
{
    // ...
};

QJSValue ObjectCreator::createObject()
{
    // No parent due to JavaScriptOwnership
    return engine_->newQObject(new SomeObj());
}

JavaScript (evaluated in engine_ from previous snippet):

function f
{
        // objectCreator is a global property of engine_
        const someObj = objectCreator.createObj();
}

Reading the documentation I couldn't find an answer to this question:

Is it valid to call engine_->newQObject() in a C++ function that is invoked via a JavaScript-script that is evaluated by engine_?

1

There are 1 answers

3
Pcgomes On

Yes, it's totally fine for a C++ to call a QJSEngine::newQObject() when called from a script.

The issue you may have is that const is not supported by ECMAScript 5, which is QJSEngine's version (see the explanation at QTBUG-69408). Replace it with var and it should work (though obviously it's not a constant).