0
votes

I'm trying to make a mouse selection rectangle.

But Rectangle {} object can't have negative width & height values.

So it only selects 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
    }
}

How can I achieve it?

Thanks!

1

1 Answers

2
votes

Here is my implementation. You just need to keep the pressed point in a property and calculate the x,y,width,height accordingly to keep width and height positive.

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;
            }
        }