我正在尝试制作一个鼠标选择矩形。
但是Rectangle {}
对象的宽度和高度值不能为负。
因此它仅选择left-to-right & top-to-bottom
:
Rectangle {
id: selectorRectangle
x: 0
y: 0
width: 0
height: 0
color: "#8000abcd"
border.color: "#00fbfb"
}
MouseArea {
anchors.fill: parent
propagateComposedEvents: true
onPressed: {
selectorRectangle.x = mouse.x
selectorRectangle.y = mouse.y
}
onPositionChanged: {
selectorRectangle.width = mouse.x - selectorRectangle.x
selectorRectangle.height = mouse.y - selectorRectangle.y
}
}
我该如何实现?
谢谢!
答案 0 :(得分:1)
这是我的实现。您只需将按下的点保持在属性中,并相应地计算x,y,width,height,以使宽度和高度为正。
Rectangle {
id: selectorRectangle
x: 0
y: 0
width: 0
height: 0
color: "#8000abcd"
border.color: "#00fbfb"
}
MouseArea {
anchors.fill: parent
propagateComposedEvents: true
property var lastPressPoint: Qt.point(0,0)
onPressed: {
lastPressPoint.x = mouse.x;
lastPressPoint.y = mouse.y;
}
onPositionChanged: {
selectorRectangle.x = Math.min(lastPressPoint.x , mouse.x)
selectorRectangle.y = Math.min(lastPressPoint.y , mouse.y)
selectorRectangle.width = Math.abs(lastPressPoint.x - mouse.x);
selectorRectangle.height = Math.abs(lastPressPoint.y - mouse.y);
}
onReleased: {
selectorRectangle.x = 0;
selectorRectangle.y = 0;
selectorRectangle.width = 0;
selectorRectangle.height = 0;
}
}