使用 When 语句的 QML 绑定滑块值

QML Binding Slider Value with When Statement

我想在 QML 中将矩形绑定到滑块。 X 轴滑块的最大值为 360。低于 180,矩形应按变化方向移动。大于 180,矩形应向变化的相反方向移动。

这是我的滑块和矩形代码片段

Slider {
        id: xAxis
        x: 60
        y: 45
        width: 200
        value: 60
        maximumValue: 360

    Rectangle {
        id: rect
        width: parent.width/10
        height: parent.height/4
        color: "transparent"
        border.color: "red"
        border.width: 5
        radius: 10
    }

绑定代码段

Binding {
        target: rect
        property: "x"
        value: (180 + (180 - xAxis.value))*(Screen.width/90)
        when: xAxis.updateValueWhileDragging && xAxis.value >= 180
    }

在那种情况下它不会更新。问题的根源是什么?

您需要为 0 到 180 之间的行为添加另一个绑定

Binding {
    target: rect
    property: "x"
    value: (xAxis.value)*(Screen.width/90)
    when: xAxis.updateValueWhileDragging && xAxis.value < 180
}