问题是一旦按下按钮,MouseArea 就会保存鼠标事件even if we move outside the area。那么另一个MouseArea就无法捕捉到鼠标事件了。
我能想象的唯一解决方案是全局管理位置变化,以便每个MouseArea 接收来自任何其他MouseArea 的positionChange 信号,并单独决定是否需要采取行动(参见mapFromItem用于位置映射):
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
visible: true
width: 500
height: 500
signal globalPositionChanged(var item, var position)
Rectangle {
id: rect1
x: 100
width: 30
height: 30
color: "red"
MouseArea {
hoverEnabled: true
propagateComposedEvents: true
anchors.fill: parent
clip: true
onPositionChanged: {
globalPositionChanged(rect1, mouse)
}
Component.onCompleted: {
globalPositionChanged.connect(handlePositionChange)
}
function handlePositionChange(item, position) {
var localPos = toLocalePosition(rect1, item, position)
if (localPos) {
// we are in the red rectangle
console.log("red", localPos.x, localPos.y)
}
}
}
}
Rectangle {
id: rect2
x: 130
width: 30
height: 30
color: "green"
MouseArea {
hoverEnabled: true
propagateComposedEvents: true
clip: true
anchors.fill: parent
onPositionChanged: {
globalPositionChanged(rect2, mouse)
}
Component.onCompleted: {
globalPositionChanged.connect(handlePositionChange)
}
function handlePositionChange(item, position) {
var localPos = toLocalePosition(rect2, item, position)
if (localPos) {
// we are in the green rectangle
console.log("green", localPos.x, localPos.y)
}
}
}
}
function toLocalePosition(toItem, fromItem, position) {
// return the local position if inside item, or null if outside
var localPos = toItem.mapFromItem(fromItem, position.x, position.y)
if (localPos.x >= 0
&& localPos.y >= 0
&& localPos.x <= toItem.width
&& localPos.y <= toItem.height) {
return localPos
}
return null
}
}
我不是 100% 相信这个答案。可能有更好的方法可以做到这一点,但我认为它可以解决您的问题。