我的分数定义如下,可以打印在屏幕上
property int score: 0
Text {
id: score1
text: "Score: "+ score
anchors.bottom: grid.top
font.pointSize: 20
color: "red"
}
和此列表模型可访问和更改网格中的正方形颜色和文本值
property variant colorArray: ["cyan","red","white"]
ListModel {
id: dummyModel
ListElement {
squareColor: "white"
txt: 0
}
ListElement {
squareColor: "white"
txt: 0
}
ListElement {
squareColor: "white"
txt: 0
}
ListElement {
squareColor: "white"
txt: 0
}
}
Timer {
// to change square colors randomly
id: alfa
interval: 2000; running: true; repeat: true
onTriggered: {
for (var i=0;i<dummyModel.count;i++) {
dummyModel.setProperty(i,"squareColor",colorArray[Math.floor(Math.random()*3)])
}
}
}
Timer {
// to change score values in grid element randomly
id: beta
interval: 2000; running: true; repeat: true
onTriggered: {
for (var i=0;i<dummyModel.count;i++) {
var sc = Math.floor(Math.random()*20) // random value from 0 to 20
dummyModel.setProperty(i,"txt",sc) // score in each square
}
}
}
此网格包含彩色正方形,当单击一个正方形且颜色为青色时,分数应通过文本字段tttt中的数字更新
Grid{
id: grid
rows: 2
columns:2
spacing: 5
anchors.centerIn: parent
Repeater{
id: gridRect
model: dummyModel // from a list element model
Rectangle{
id: rect
width: 50
height: width
color: "cyan"
radius: 10
Text {
id: tttt
anchors.centerIn: parent
color: "lightBlue"
text : txt
}
MouseArea{
anchors.fill: parent
onClicked: {
if (rect.color == "cyan")
score = score + tttt.text
else if (rect.color == "red")
score = score - tttt.text
}
}
}
}
}
但是点击时无法更新得分,而是出现此错误/警告:
<Unknown File>: Can't assign to existing role 'txt' of different type [Number -> String]
那是为什么?
答案 0 :(得分:0)
Text组件可以接收任何类型的数据:字符串,数字等,并尝试将其转换为字符串,在您使用txt.text的情况下,您将获得该转换后的字符串。因此,有两种解决方案将字符串转换为数字,或者最好不要使用Text组件的值,而要使用模型的属性:
// ...
Rectangle{
id: rect
width: 50
height: width
color: model.squareColor
radius: 10
Text {
id: tttt
anchors.centerIn: parent
color: "lightBlue"
text : model.txt
}
MouseArea{
anchors.fill: parent
onClicked: {
if (model.squareColor === "cyan")
score = score + model.txt
else if (model.squareColor === "red")
score = score - model.txt
}
}
}
// ...