Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does QML engine instantiate the same script multiple times?

Tags:

javascript

qt

qml

Assume that we have the following JS file:

logic.js

function Car(){}

and these QML files:

comp1.qml

import 'qrc:/js/logic.js' as Logic

Item{
    property var item: Logic
}

comp2.qml

import 'qrc:/js/logic.js' as Logic

Item{
    property var item: Logic
}

If you run and evaluate, you'll see that those item properies are not equal. Why?

In my application, in one QML file I new an object and would like to check whether it's instanceof a constructor function or not, but since those constructor functions aren't equal (because those Logics aren't), instanceof operator always returns false.

like image 416
frogatto Avatar asked Mar 02 '26 23:03

frogatto


1 Answers

The Code-Behind Implementation Resource documentation explains this behaviour:

Most JavaScript files imported into a QML document are stateful implementations for the QML document importing them. In these cases, each instance of the QML object type defined in the document requires a separate copy of the JavaScript objects and state in order to behave correctly.

The default behavior when importing JavaScript files is to provide a unique, isolated copy for each QML component instance. If that JavaScript file does not import any resources or modules with a .import statement, its code will run in the same scope as the QML component instance and consequently can access and manipulate the objects and properties declared in that QML component. Otherwise, it will have its own unique scope, and objects and properties of the QML component should be passed to the functions of the JavaScript file as parameters if they are required.

The solution is to put .pragma library at the top of your JavaScript file. This will allow it to be shared by several QML files.

The next section, Shared JavaScript Resources (Libraries) goes into more detail about this.

like image 123
Mitch Avatar answered Mar 04 '26 13:03

Mitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!