If statement in QML

天大地大妈咪最大 提交于 2019-12-10 01:57:07

问题


Completely new to QT and QML. I'm trying to set the color of a rectangle based on the relationship between the two propery doubles callValue and handRaiseXBB, but I get the error

unexpected token if"

and

expected a qualified name id

Could anyone tell me what I am doing wrong?

import QtQuick 2.0

Item{
    id: hand

    property double callValue: 0.0

    property double handRaiseXBB: 100
    property string handCallColor: "green"
    property string handFoldColor: "grey"

    Rectangle {
        anchors.fill: hand
        if (hand.callValue >= hand.handRaiseXBB) {
            color: hand.handFoldColor
        }
        else {
            color: hand.handCallColor
        }
    }
}

回答1:


You can do it like this:

color: (hand.callValue >= hand.handRaiseXBB) ? hand.handFoldColor : hand.handCallColor

You could also make a function to calculate it and then assign the color property with the return value of the function:

function getHandColor()
{
    var handColor = hand.handCallColor
    if(hand.callValue >= hand.handRaiseXBB)
    {
        handColor = hand.handFoldColor
    }
    return handColor
}
color: getHandColor()



回答2:


Another form to solve this is the following:

Rectangle {
    ...
    color: {
       color = hand.handCallColor
       if(hand.callValue >= hand.handRaiseXBB)
           color = hand.handFoldColor
    }
    ...
}

But the form with ternary operator is a better form!

QML is "based" in javascript, then i belive that all itens are javascript objects, how to:

var Rectangle: {
   color: "red",
   id: "id",
   //then we can do this
   setColor: function(_color) {this.color = _color}
}


来源:https://stackoverflow.com/questions/24639431/if-statement-in-qml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!