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

Ulf Hermann ulf.hermann at qt.io
Wed Apr 15 10:05:48 CEST 2020


> Is there a way to set a QJSValue as a context property in QQmlContext and
> retain function properties?

You should not do this. Context properties are invisible to any tooling 
or static analysis of your QML code and add significant complication to 
the name lookup logic. The fact that you can inject names into QML this 
way is one of the few reasons why we need to version our imports. In Qt6 
we aim to move away from this.

> 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.

best regards,
Ulf


More information about the Interest mailing list