QML - MouseArea/MouseEvent 问题

2024-02-27

下面的代码生成一个白色矩形,其中包含一个红色矩形和一个灰色矩形。每个矩形都有一个关联的 MouseArea。当鼠标在灰色矩形内单击时,灰色矩形会变成蓝色。当鼠标光标进入红色矩形内部时,红色矩形会打印一条控制台消息,当发出释放信号时,会打印另一条消息。

我想:

  1. 在灰色矩形内按住鼠标按钮(变成蓝色)
  2. 将光标移到灰色/蓝色矩形之外,然后移到红色矩形内部,不释放按钮并捕获红色矩形的输入信号
  3. 释放光标在红色矩形内的按钮并捕获红色矩形释放的信号。

是否可以?使用当前代码,仅当输入时未按下鼠标按钮时才会发出红色矩形的输入信号,并且仅当在该矩形内按下按钮时才会发出释放信号。显然,问题在于,如果按下按钮,灰色/蓝色矩形将控制鼠标事件。

这是与我正在开发的应用程序中遇到的场景类似但经过简化的场景。

import QtQuick 2.0

Rectangle{
    color: "white"
    height: 210
    width: 500

    MouseArea{
      id: mainMa
      anchors.fill: parent
      hoverEnabled: true
      onReleased:{console.log("white-released")}
   }

   Column{
       spacing: 10
       Rectangle{
           color: "red"
           height: 100
           width: 500
          MouseArea{
             anchors.fill: parent
             hoverEnabled: true
             propagateComposedEvents: true
             onEntered:{console.log("red-enter")}
             onReleased:{console.log("red-released")}
          }
       }

       Rectangle{
           color: "#666666"
           height: 100
           width: 500
           MouseArea{
               id: ma
               anchors.fill: parent
               hoverEnabled: true
               onPressed: {parent.color = "blue"; console.log("grey pressed")}
               onReleased: {parent.color = "#666666"; console.log("grey released")}
           }
       }
   }

}


我认为您需要拖放操作。为此,在红色矩形中添加 DropArea 并在灰色矩形中添加活动拖动

类似的东西(最少的代码):

Rectangle {
    Column {
        Rectangle {
            id: redRect
            DropArea {
                anchors.fill: parent
                onEntered: { console.log("red-enter") }
                onDropped: { console.log("red-released") }
            }
        }
        Rectangle {
            id: greyRect
            Drag.active: mousearea.drag.active
            Drag.hotSpot.x: mousearea.mouseX
            Drag.hotSpot.y: mousearea.mouseY
            MouseArea {
                id: mousearea
                anchors.fill: parent
                onReleased: parent.Drag.drop()
                drag.target: parent
            }
        }
    }
}

如果你不想移动灰色矩形,你可以添加不可见的可拖动项:

    MouseArea {
    id: mousearea
    anchors.fill: parent
    onReleased: dargItem.Drag.drop()
    drag.target: dargItem
    Item {
        id: dargItem
        x: mousearea.mouseX
        y: mousearea.mouseY
        width: 1; height: 1
        Drag.active: mousearea.drag.active
        Drag.hotSpot.x: 1
        Drag.hotSpot.y: 1
    }                    
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

QML - MouseArea/MouseEvent 问题 的相关文章

随机推荐