O'Reilly logo

Game Programming using Qt 5 Beginner's Guide - Second Edition by Lorenz Haas, Witold Wysota, Pavel Strakhov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required