Creating global variables using JavaScript for QML

I have a problem with QML / JS integration.

I have a javascript list variable stored in a .js file. I want to write this variable from one QML file and read it from another QML file. I can't seem to find a solution. I have simplified my actual code too much to make it clear!

// writeValue.QML import "../javascript/storedValue.js" as StoredValue ... MouseArea{ onClicked{ StoredValue.value.push(1) } } // readValue.QML import "../javascript/storedValue.js" as StoredValue ... Text{ text : StoredValue.value } //storedValue.js var value = [] 

I tried using the '.pragma library' and did not use it, but to no avail.

What happens, write writeValue.QML succeeds, therefore [1, 1, 1, ...]. While readValue.QML just finds an empty list, [].

+4
source share
1 answer

Just put the .pragma library at the top of the JS file. Thus, only one instance is imported by QML components.

Remember, however, that when the var property is changed, the update signal does not appear. If you want to have a global var with update support, you must export a custom QObject via setContextProperty() on the C ++ side.

+5
source

Source: https://habr.com/ru/post/1487289/


All Articles