【问题标题】:QML how to set color in a mouseAreaQML如何在鼠标区域中设置颜色
【发布时间】:2017-06-14 08:52:52
【问题描述】:

我想设计如下按钮布局:

它有一个位于蓝色背景之上的重启按钮图像。我想使用 QML 在 Qt 中复制相同的内容。我正在使用 MouseArea Qt Quick 对象,我在 Stretch 填充模式下重叠图像。但是,没有为鼠标区域获得蓝色背景的选项。目前它看起来像这样:

相同的对应代码:

MouseArea {
    id: restartbutton
    x: 669
    width: 50
    height: 50
    opacity: 1
    antialiasing: false
    hoverEnabled: true
    anchors.top: parent.top
    anchors.topMargin: 8
    z: 1

    Image {
        id: image2
        anchors.fill: parent
        source: "restart_icon.png"
    }

}

如何在此处设置 MouseArea 的背景?

【问题讨论】:

    标签: qt qml qtquick2 mousearea


    【解决方案1】:

    您可能想像这样使用Rectangle

    Rectangle {
      width:50
      height: 50
      Image {
        anchors.fill:parent
        source: "restart_icon.png"
      }
      MouseArea {
        anchors.fill:parent
        onClicked: {...}
      }
    }
    

    查看QML Advanced Tutorial 了解更多信息

    【讨论】:

    • 嗨!要改进此答案,您可以在示例中实际设置背景颜色
    • 另外,最好将MouseArea 作为根节点(将RectangleMouseArea 交换)然后将Rectangles color 公开为property alias background: myRect.color .原因是,MouseAreaRectangle 具有更多可能与公开相关的信号和属性。如果您想拥有一个干净的界面并且只公开最少的接口,那么Item 作为 root 将是替代方案。
    • 是的,这行得通。就像@derM 所说,最好将 MouseArea 作为 root。
    【解决方案2】:

    我认为这样更容易阅读:

       MouseArea { id: clickArea
            anchors {
                fill: parent 
                margins: -10   // optional to enlarge the backgound / click zone
            }
            onClicked: {
                console.log("clicked!")
            }
            Rectangle {  // background, also allowing the click
                anchors.fill: clickArea
                border.color: "black"
                color: "lightblue"
                opacity: 0.3
            }
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      相关资源
      最近更新 更多