【问题标题】:Qt5 QML how to prevent Slider rogue initial valueQt5 QML如何防止Slider rogue初始值
【发布时间】:2016-04-14 16:42:15
【问题描述】:

我有一个Slidervalue 读取我的持久值,onValueChanged 写入它。但是,将 minimumValue 设置为 1,会在我的 value 初始访问之前调用 onValueChanged。这会导致我的持久值始终被覆盖为 1。

例如

Slider
{
    stepSize: 1
    minimumValue: 1  // this happens before `value` regarless of order here
    maximumValue: 5
    value: myPersistentValue
    onValueChanged:
    {
        // gets called *before* myPersistentValue is accessed and overwrites it!
        myPersistentValue = value
    }
}

有什么方法可以防止这种情况或以某种方式测试准备情况吗?

谢谢。

【问题讨论】:

  • 这是一个依赖循环,无效。你必须做点别的,这永远行不通。它只是碰巧起作用,因为 QML 引擎会为您打破依赖循环,作为防止崩溃/冻结 GUI 的最后手段。

标签: qt qml qt5


【解决方案1】:

我认为解决此问题的最佳方法是使用 bool 来控制 Slider 是否已完成,因此 myPersistentValue 只有在 Slider 已完成时才会更改。

类似这样的:

import QtQuick 2.5
import QtQuick.Controls 1.4

ApplicationWindow {
    id: rootWindow
    objectName: "window"
    visible: true
    width: 200
    height: 200

    property int myPersistentValue: 5

    Slider
    {
        id: mySlider
        stepSize: 1
        minimumValue: 1
        maximumValue: 5
        value: myPersistentValue

        property bool completed: false

        onValueChanged:
        {
            console.log("slider - onValueChanged: " + myPersistentValue +
                        " value: " + value )

            if (completed) {
                console.log("slider - onValueChanged & completed: " + myPersistentValue +
                            " value: " + value )
                myPersistentValue = value
            }
        }

        Component.onCompleted: {
           console.log("Slider completed!")
           completed = true
        }
    }


    Button
    {
        y: 50
        text: "click me!"
        onClicked: {
            myPersistentValue = myPersistentValue - 1
            console.log("button - onClicked: " + myPersistentValue)
        }
    }
}

如果 QML 标准组件有这些信息我会很好,但恐怕没有。

顺便说一句,令人惊讶的是,如果您将minimumValue 设置为小于或等于0,则行为会有所不同。在初始化过程中,onValueChanged 只被调用一次,value 等于myPersistentValue

【讨论】:

  • 您的答案是我找到的解决此问题的最简单方法。我觉得必须有一个属性来确保滑块准备好有点假。感谢您的帮助。
  • 要节省几行代码,您可以使用readonly property bool completed: Component.completed
猜你喜欢
  • 1970-01-01
  • 2020-10-21
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 2022-01-19
相关资源
最近更新 更多