Qt and Javascript^WQtScript
Today (at dawn) I had my first experience with Javascript inside Qt. The language is actually referred as QtScript by Qt documentation. The thing is simply great. Executing simple Javascript code is simple as
QScriptEngine engine;
qDebug() << engine.evaluate("a = 1; b = 2; a + b;").toInt();
As expected, the "protocol" between C++ and Javascript objects has its rules. Javascript can't "see" the current application's context. For exemple, if we want to make an object available to Javascript, we must add it to the global scope:
engine.globalObject().setProperty("close_button", closeButton);
When an object is made available in Javascript context, the following features (among others) are made available from Javascript side:
a) properties can be set and get using the obj.property syntax. Yet another incentive to use Qt properties as much as possible in our C++ classes.
b) public slot methods can be called (as normal methods) from Javascript, since Qt has introspection information about them. Too good that exporting methods as slots costs nothing.
c) signals and slots can be used (connected and fired at will). Slot functions may be written in Javascript. The only limitation is that signals must be defined in C++; you can not define a new signal in Javascript.
Non-slot methods must be encapsulated to be made available. The easiest way is to connect them to properties, which in turn are always available in Javascript space.
Perhaps unexpectedly, class constructors are not made automatically available to Javascript. Constructors and C++ free functions must be added to Javascript by encapsulating them in QScriptValue objects and then adding them to Javascript scope the same way we did with closeButton.
This means that, for now, QtScript can not be used to write whole applications, because it always depends on a C++ supportive "shell" to make the right objects and classes available for scripting.
I guess the problem can be mitigated somewhat by using factories in C++; if you use factory("AnyClass") to instantiate objects, it is just a matter of exporting the factory() to Javascript. Of course, this leaves the Qt classes themselves out.
If we want to use some Javascript in our Qt apps, there are some architectural trends that we must follow. Using properties, signals/slots and factories instead of static method calls everytime we can. And leave behind the anal-retentive mania of keeping most methods protected/private. Those techniques make life easier in C++ anyway, so why not?

