[Interest] How to set a QJSValue with functions as a context property in QQmlContext?

Richard Weickelt richard at weickelt.de
Wed Apr 15 15:42:25 CEST 2020


Thanks for your reply.

> 
>> I am loading a .js file with QJSEngine::importModule(). The result is
>> QJSValue object containing all exported functions and properties from the
>> module.
>>
>>      // file.js
>>      export function someFunction(someArg) {
>>          return someArg;
>>      }
>>      export someVar = "value";
>>
>>      // importing code
>>      QJSValue module = engine->importModule("/path/to/file.js");
>>
>> Now I want to evaluate JS code snippets with my modules installed. I need
>> fine-grained control over contexts and my real-world application uses a
>> context hierarchy. So I use QQmlExpression and set my imported module as a
>> context property:
> 
> Why do you need to do this with contexts? I would suggest a singleton to
> hold the QJSValue, or a QML file that imports the JavaScript itself. In both
> ways you get a declared name as scope for your script, which avoids the name
> injection.

I am not loading QML documents at all nor do I need QML tooling here. This
is pure JS. I have a bunch of JS code snippets to evaluate. The snippets
expect certain properties to exist, but they do not necessarily share the
same context. Some of them do though.

I am afraid that your suggestion would require me to modify the global
object before evaluating each code snippet or at least to create a private
QJSEngine instance for each which I deem is slow. Is that assumption correct?

The final goal is to port the scripting backend of Qbs from QtScript over to
the V4 engine, but I am still at the very beginning. Although Qbs files look
like QML, we are not using the QML machinery. Instead, we use only the QML
parser to decompose the document structure and retrieve items and property
declarations/assignments. The resulting code snippets (property assignments)
are then evaluated in different contexts. We have different context levels,
e.g. a document context for imported JS modules, a product context for
properties related to the current product, and a property context where we
provide properties like "base" referring to the base class value.

Best regards
Richard


More information about the Interest mailing list