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

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


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

OK, that does paint a different picture. The feature you are asking for, 
then, is for QJSEngine to allow defining ECMAScript modules from C++, 
that can be imported in your JavaScript files via standard ECMAScript 
"import" statements. I would not be automatically opposed to such a feature.

However, as all of your code seems to be JavaScript anyway, why don't 
you write everything as real ECMAScript modules in the first place? 
AFAICS the C++ code in your example is only used for plumbing. Is that so?

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

import * from "documentFooBar"
import * from "productA"
import base from "propertySomething"

The respective .mjs files would be modules that set up the required 
stuff in JavaScript. You can also put import statements into any 
dynamically evaluated JavaScript snippets.

The nice thing about importing things explicitly is that the JS engine 
knows what is there already when compiling.

best regards,
Ulf


More information about the Interest mailing list