[Interest] Creating C++ objects in JavaScript with operator new

Richard Weickelt richard at weickelt.de
Mon Apr 15 22:10:04 CEST 2019


Hi,

is there an easy way to register a QObject-derived class in the QML type
system so that I can instantiate it from within JavaScript code using
operator new?

function someJavaScriptFunction(){
    var myObject = new MyClass("blabla");
    // ...
}

Right now I am registering another class as a proxy which then registers the
constructor function for my class. This looks overly verbose and clunky. Is
there a simpler way?


class MyClass : public QObject
{
    Q_OBJECT
public:
    MyClass(QObject* parent = nullptr, const QString& someParam = "");

    Q_INVOKABLE bool someMethod() const;
    static void registerAsJSType(QJSEngine* engine);
};

class MyClassCreator : public QObject
{
    Q_OBJECT
public:
    Q_INVOKABLE MyClass* createObject(const QVariantMap& arguments);
};

void MyClass::registerAsJSType(QJSEngine* engine)
{
    QJSValue creator = engine->newQObject(new MyClassCreator());
    engine->globalObject().setProperty("_MyClassCreator", creator);
    engine->evaluate("function MyClass(param) { return
_MyClassCreator.createObject({ someParam: param }); }");
}

MyClass* MyClassCreator::createObject(const QVariantMap& arguments)
{
    QString someParam = arguments.value("someParam").toString();
    return new MyClass(qmlEngine(this), someParam);
}


Thanks
Richard


More information about the Interest mailing list