qt - 为什么我不能打印更新的分数?
问题描述
我有如下定义的分数要打印在屏幕上
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]
这是为什么?
解决方案
Text 组件可以接收任何类型的数据:字符串、数字等,并尝试将其转换为字符串,在您使用 txt.text 的情况下,您将获得转换后的字符串。所以有2种解决方案将字符串转换为数字,或者最好不要使用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
}
}
}
// ...
推荐阅读
- html - 如何让两种悬停效果都发生?
- vue.js - Vue.js - 如何将美元符号插入主 index.html 文件
- sql - DataStudio 上的数组过滤器
- javascript - 如何将 cloudinary 与 ant 设计上传组件一起使用?
- javascript - 错误代码 401,HTTP 令牌:访问被拒绝
- python - 如何允许用户在 Django 中的颜色主题之间切换
- sql - 删除表中所有记录(如果存在)的最有效方法
- java - JavaFX:如何获取特定选项卡来执行操作
- c++ - 对纯右值调用的 std::move 是否解构对象?
- python - 使用 Flask (python) 将表单输出发送到同一网页上的 if 语句