Creating C++ objects from JavaScript

We've only exposed the existing C++ objects to JavaScript so far, but what if you want to create a new C++ object from JavaScript? You can do this using what you already know. A C++ method of an already exposed object can create a new object for you:

public:
    Q_INVOKABLE QObject* createMyObject(int argument) {
        return new MyObject(argument);
    }
We use QObject* instead of MyObject* in the function signature. This allows us to import the object into the JS engine automatically. The engine will take ownership of the object and delete it when there are no more references to it in JavaScript.

Using this method from JavaScript is also pretty straightforward:

var newObject = originalObject.createMyObject(42); newObject.slot1(); ...

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.