首页 文章

对于QML,为什么LayoutMirroring在Slider中不起作用?

提问于
浏览
0

今天我尝试了QtQuick.Controls中的Slider,我的滑块是从左到右,我想通过使用 LayoutMirroring.enabled 从右到左设置我的滑块,最后我发现我无法反转滑块 .

这是我的小演示代码,那么我们如何反转滑块呢?

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Slider{
        id:test
        value: 0.2
        width:400
        LayoutMirroring.enabled: true
    }
}

1 回答

  • 1

    如果你使用 Slider 来自 QtQuick.Controls 2.x - 至少对我来说 - 它就像一个魅力 . 如果您使用 Slider 来自 QtQuick.Controls 1.x 则不然 .

    来自documentation

    但请记住,镜像不会影响Item x坐标值定义的任何定位,因此即使启用了镜像,通常也需要应用一些布局修复来支持所需的布局方向 .

    但是 QtQuick.Controls 1.x - Slider 使用基于坐标的implementation,并且没有进一步的预防措施来支持 LayoutMirroring .

    但是 Slider 的布局通常是对称的,因此您需要做的就是将值映射为(0,1)到(1,0) . 这对开发人员来说应该是一件容易的事 .

    import QtQuick.Controls 1.3
    import QtQuick.Controls.Layouts 1.3
    import QtQuick.Controls.Private 1.3 // Needed for a mysterious value from the original, now mirrored style.
    Slider {
        y: 40
        id: sli
        width: parent.width
        minimumValue: 50
        maximumValue: 100
    
        property real mirroredValue: maximumValue - value + minimumValue
    
        // Invert style
        style: SliderStyle {
            groove: Item {
                property color fillColor: "#49d"
                anchors.verticalCenter: parent.verticalCenter
                // Whatever TextSingleton is. You need to import QtQuick.Controls.Private 1.x for it.
                implicitWidth: Math.round(TextSingleton.implicitHeight * 4.5) 
                implicitHeight: Math.max(6, Math.round(TextSingleton.implicitHeight * 0.3))
                Rectangle {
                    radius: height/2
                    anchors.fill: parent
                    border.width: 1
                    border.color: "#888"
                    gradient: Gradient {
                        GradientStop { color: "#bbb" ; position: 0 }
                        GradientStop { color: "#ccc" ; position: 0.6 }
                        GradientStop { color: "#ccc" ; position: 1 }
                    }
                }
                Item {
                    clip: true
                    x: styleData.handlePosition // let the fill-stuff start at the handle position...
                    width: parent.width - styleData.handlePosition // and end at the end of the groove.
                    height: parent.height
                    Rectangle {
                        anchors.fill: parent
                        border.color: Qt.darker(fillColor, 1.2)
                        radius: height/2
                        gradient: Gradient {
                            GradientStop {color: Qt.lighter(fillColor, 1.3)  ; position: 0}
                            GradientStop {color: fillColor ; position: 1.4}
                        }
                    }
                }
            }
        }
    }
    

    如果您不想设置滑块的值,则需要在 mirroredValuevalue 之间安装bidirectional binding .

相关问题