QML矩形,负宽度,用于鼠标选择

我正在尝试制作一个鼠标选择矩形。

但是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
    }
}

我该如何实现?

谢谢!

dianxinwad 回答:QML矩形,负宽度,用于鼠标选择

这是我的实现。您只需将按下的点保持在属性中,并相应地计算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;
            }
        }
本文链接:https://www.f2er.com/3168529.html

大家都在问