Bindings Question in Qt
-
Hi everybody,
I see a different behavior when you binds a simple var and an array.
For example, with this QML code:import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.3 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") property var testArray: [1,2,3,4,5] property var test: 1 Button { text: "click me" property var testArrayHierachy: testArray property var testHierachy onClicked: { console.log(test); testHierachy = 9; console.log(test); //When Array console.log(testArray); testArrayHierachy[0] = 9; console.log(testArray); } } }
When I click the button the results are:
qml: 1
qml: 1
qml: [1,2,3,4,5]
qml: [9,2,3,4,5]Why when it's just a variable if you modify a value of one of the two binded items the other one does not change and when it's an array the both items are modified. It's for the same reason that in JavaScript in functions an array as a parameter is passed as a reference?
And, this is the expected result? Or it's a bug?Thank you very much.
-
This is more of how arrays work in Javascript. It is question of pass-by-value or pass-by-reference. If u are assigning the individual values they works as it is pass-by-reference. If you are setting the value of Array itself, then it will act like pass-by-value.
Just try with additional stuff like the follows.
```
onClicked: {
console.log(test);
testHierachy = 9;
console.log(test);
//When Array
console.log(testArray);
testArrayHierachy[0] = 9;
console.log(testArray);
testArrayHierachy = [10,20,30,40,50]
console.log(" OLD="+testArray);
console.log(" New="+testArrayHierachy);
}Now number changes by reference. But assigning the array to testArrayHierachy new array values does not change the testArray.