【问题标题】:How to initialize a property of a custom item from outside without breaking the internal bindings?如何在不破坏内部绑定的情况下从外部初始化自定义项的属性?
【发布时间】:2020-09-28 22:08:45
【问题描述】:

我正在尝试为 HSL 组件制作一个带有三个滑块的颜色调整面板。它由一个可重复使用的ColorPanel 项目组成:

Item {
    id: root

    property color color: Qt.hsla(sliderH.value, sliderS.value, sliderL.value, 1.0)

    implicitWidth: 300; implicitHeight: 100

    Rectangle { anchors.fill: parent }

    Column {
        width: parent.width

        Slider { id: sliderH }
        Slider { id: sliderS }
        Slider { id: sliderL }
    }
}

我在main.qml 中使用了两次,一次用于调整Label 的背景颜色,另一次用于调整文本颜色:

ApplicationWindow {
    width: 500; height: 400
    visible: true
    title: qsTr("Color Setup")

    header: RowLayout {
        spacing: 10

        ColorPanel { id: colorText }
        ColorPanel { id: colorBackground }
    }

    Label {
        anchors.centerIn: parent
        color: colorText.color
        text: qsTr("How to initialize the colors?")
        font.pointSize: 22; padding: 11

        background: Rectangle { color: colorBackground.color }
    }
}

这个非常简短的示例生成以下 UI:

我确实可以通过用鼠标移动滑块来设置Label 的背景和前景(文本)颜色。但是,在程序启动时,Label 是黑色的,因为滑块位于0。我当然可以将它们设置为不同的值,但这无济于事,因为它仍然会导致两种颜色相同并且文本仍然不可见。所以,我需要将两个面板的color 属性初始化为不同的值。

问题是,当我写这样的东西来初始化颜色时:

ColorPanel { id: colorText; color: "red" }
ColorPanel { id: colorBackground; color: "green" }

颜色确实在启动时设置为所需的值,但新绑定打破了与Qt.hsla(sliderH.value, sliderS.value, sliderL.value, 1.0) 的内部绑定,并且无法再使用滑块设置颜色。

accepted answerHow to set initial value of a custom slider in qml? 建议将属性设为别名,例如property alias color:,但我应该参考什么?

如何解决?

【问题讨论】:

  • 我不喜欢它们,因为用户倾向于询问 DV 原因。 DV和UV都不需要辩解,我没有看到指向用户:他们为什么要给我UV?也没有必要证明最后的投票是合理的。上面的逻辑是社区长期平衡投票,如果你的帖子好你会得到比DV多得多的UV,如果不是那么你会得到相反的结果。请阅读meta.stackoverflow.com/questions/285081/…
  • @eyllanesc,是的。你是对的。

标签: windows qt qml qt5


【解决方案1】:

您可以将initialColor 属性添加到您的ColorPanel 并将滑块连接到它,如下所示:

Item {
    id: root

    property color initialColor
    property color color: Qt.hsla(sliderH.value, sliderS.value, sliderL.value, 1.0)

    implicitWidth: 300; implicitHeight: 100

    Rectangle { anchors.fill: parent }

    Column {
        width: parent.width

        Slider { id: sliderH; value: initialColor.hslHue }
        Slider { id: sliderS; value: initialColor.hslSaturation }
        Slider { id: sliderL; value: initialColor.hslLightness }
    }
}

然后在main.qml 中而不是color 中,使用initialColor,如下所示:

ColorPanel { id: colorText; initialColor: "red" }
ColorPanel { id: colorBackground; initialColor: "green" }

【讨论】:

  • 哇,很棒的解决方案!完美运行,稍作修正:L 代表 lightness,而不是 luminance,但我已经更正了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
  • 2020-12-28
  • 1970-01-01
相关资源
最近更新 更多