qtqt5qjsengine

Multiple instances of QJSEngine within a single app?


Is it normal for a single C++/Qt5 app to have multiple independent instances of JavaScript engine? In my app, I have several QObject-inherited objects which act as independent data-processing units. In each of them, I want to be able to launch JS scripts, and I want contexts of those scripts to be independent among these units. The simplest idea is to make each of the units to have its own instance of QJSEngine. A simple test shows that if I create two engines in the same app and set a custom global property in one of them, this property is not known to the second engine, which is what I want. But still it is not obvious that there are no some global state-properties which are common to all instances of QJSEngine. The issue of multiple instances seems to be never mentioned in the official Qt docs. Is that sufficient to conclude that having multiple instances poses no problems?


Solution

  • Qt documentation are generally explicit, so if it would be forbidden to create 2 QJSEngine it would be written in the documentation and you would have a warning or an assert failure at run-time.

    For instance, if you try to create 2 QCoreApplication instances, you end up with a crash with the error:

    ASSERT failure in QCoreApplication: "there should be only one application object", file kernel\qcoreapplication.cpp, line 792
    

    Since there are no such notice/warning/assert for QJSEngine, it should be perfectly safe to create multiple instances.

    If you want yet another tip that this is allowed, you can look at QQuickWidget. This widget will create its own QQmlEngine (i.e. QJSEngine) if needed, regardless of the existence of any other QJSEngine or QQmlEngine instance.