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

Accessing C++ object's properties and methods

The simplest way to expose a C++ object to JavaScript code is to take advantage of Qt's meta-object system. QJSEngine is able to inspect QObject instances and detect their properties and methods. To use them in scripts, the object has to be visible to the script. The easiest way to make this happen is to add it to the engine's global object. As you remember, all data between the script engine and C++ is exchanged using the QJSValue class, so first we have to obtain a JS value handle for the C++ object:

QJSEngine engine;
QPushButton *button = new QPushButton("Button");
// ...
QJSValue scriptButton = engine.newQObject(button);
engine.globalObject().setProperty("pushButton", scriptButton); 

QJSEngine::newQObject() ...

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