Reputation: 17602
I am creating some Rectangle
s dynamically with a Text
element inside like so:
Rectangle {
id: root
width: 640; height: 480
property var items: []
property int count
function push() {
var temp = Qt.createQmlObject("import QtQuick 2.3; Rectangle {width: 100; height: 30;color: 'yellow'; Text {text: count; anchors.centerIn: parent}}", root, "")
temp.x = Math.floor(Math.random()*200 + 1)
temp.y = Math.floor(Math.random()*200 + 1)
items[count] = temp
count++
}
MouseArea {
anchors.fill: parent
onClicked: push()
}
}
Now, whenever I call the push
function by clicking, it creates a new rectangle with present value of count
. But the problem is all rectangles created so far change their text to present value of count
. I need to create rectangles with present value of count and they should not change their text when count
changes afterwords. How can I do this? Thanks!
Upvotes: 0
Views: 725
Reputation: 7150
The Rectangle
s you are creating have this code :
Text {
text: count
anchors.centerIn: parent
}
Here, there is a binding between the text
property and count
. So whenever the count
changes, the text
will reflect that change.
You need to escape the count in your string definition to actually concatenate the current value of count
so that the code for the first item is :
Text {
text: '0'
anchors.centerIn: parent
}
You code shoud then be :
Rectangle {
id: root
width: 640; height: 480
property var items: []
property int count
function push() {
var temp = Qt.createQmlObject("import QtQuick 2.3; Rectangle {width: 100; height: 30;color: 'yellow'; Text {text: '"+count+"'; anchors.centerIn: parent}}", root, "")
temp.x = Math.floor(Math.random()*200 + 1)
temp.y = Math.floor(Math.random()*200 + 1)
items[count] = temp
count++
}
MouseArea {
anchors.fill: parent
onClicked: push()
}
}
Upvotes: 2