首页 > 解决方案 > 为什么我不能打印更新的分数?

问题描述

我有如下定义的分数要打印在屏幕上

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]

这是为什么?

标签: qtqml

解决方案


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
        }
    }
}
// ...

推荐阅读