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

Exposing C++ functions to JavaScript

Sometimes you just want to provide a single function instead of an object. Unfortunately, QJSEngine only supports functions that belong to QObject-derived classes. However, we can hide this implementation detail from the JavaScript side. First, create a subclass of QObject and add an invokable member function that proxies the original standalone function:

Q_INVOKABLE double factorial(int x) {
    return superFastFactorial(x);
}

Next, expose the wrapper object using the newQObject() function, as usual. However, instead of assigning this object to a property of the global object, extract the factorial property from the object:

QJSValue myObjectJS = engine.newQObject(new MyObject()); engine.globalObject().setProperty("factorial", ...

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