[Interest] QtScript to QJSEngine migration

Julien Cugnière julien.cugniere at gmail.com
Mon Jun 22 17:17:01 CEST 2015


Hi all,

With QtScript deprecated in Qt 5.5, and likely removed in a future
version, I'm looking at how to migrate to QJSEngine. There are some
things I'm not sure how best to achieve with the new minimalist API :

1. Exposing a global function to Javascript from C++.

In QtScript, one could write a C++ function with the signature "
QScriptValue f(QScriptContext*, QScriptEngine*) ", and expose it
directly in a global variable. I found no equivalent in QJSEngine. If
I understand correctly, I can only expose QObjects, so the best I
could come up with is the following :

 * write my functions as Q_INVOKABLE members in a QObject.
 * expose that QObject using QJSEngine::newQObject.
 * iterate over the object with QJSValueIterator, and copy the
function properties to the global object.

Is there a better way available, or planned ? If not, would a merge
request to add the above to the documentation be accepted ? (probably
somewhere in "Making Applications Scriptable").

2. Writing a variadic function from C++.

In QtScript this could be done with the QScriptContext* parameter.
With QJSEngine, the best I've come up with is this :

 * write a wrapper function in javascript forwarding the "arguments" object :
   " function foo() { return Foo.foo_impl(arguments); } "
 * write foo_impl in C++ as a Q_INVOKABLE member taking a single
QJSValue parameter.

Is there a better way ? And again, is this worth adding to the documentation ?

3. How to raise a Javascript error from a function implemented in C++.

This is basically https://bugreports.qt.io/browse/QTBUG-39041, which
has seen no comment for the past year. Is something similar planned ?
Otherwise the only solution I see is again a wrapper function written
in Javascript. Something like this :

    function foo() {
       var res = foo_impl();
       if (Object.getPrototypeOf(res) === Error)
            throw res;
       else
           return res;
    }

-- 
Julien Cugnière



More information about the Interest mailing list