Home > database >  How to invert mouse cursor behaviour in Mouse Area
How to invert mouse cursor behaviour in Mouse Area

Time:10-26

I want to invert direction of mouse cursor. For example when I move mouse right - cursor move to left, when I move mouse up - cursor move to down. And I want do it if mouse on pressed left button.

CodePudding user response:

You can hide the real cursor and place a fake cursor in a different position. In the following example:

  • A define a Rectangle where the reverse mouse area applies
  • MouseArea requires containsMouse and pressed before reverse mode is actived
  • MouseArea hides the real mouse with Qt.BlankCursor
  • Will display a fake mouse using an SVG recreation of the mouse cursor
  • When the reverse mode is enabled we flip the coordinates of the fake mouse with parent.width - mouseArea.mouseX and parent.height - mouseArea.mouseY
import QtQuick
import QtQuick.Controls
Page {
    Rectangle {
        anchors.centerIn: parent
        color: "#ffe"
        border.color: "grey"
        width: Math.floor(parent.width / 2)
        height: Math.floor(parent.height / 2)

        Image {
             id: fakeMouse
             x: mouseArea.reversed
                     ? parent.width - mouseArea.mouseX
                     : mouseArea.mouseX
             y: mouseArea.reversed
                     ? parent.height - mouseArea.mouseY
                     : mouseArea.mouseY
             visible: mouseArea.containsMouse
             source: "cursor-32.svg"
        }

        MouseArea {
            id: mouseArea
            property bool reversed: pressed & containsMouse
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.BlankCursor
        }

        Frame {
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.bottom: parent.bottom
            anchors.margins: 10
            visible: fakeMouse.visible
            Label {
                 text: fakeMouse.x   " "   fakeMouse.y
            }
        }
    }
}

//cursor-32.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path d="M9 25.282l4.3-5.894 4.062 8.043 5.016-2.523L18.416 17h7.01L9 5.016zm.99-18.318l12.398 9.046h-5.575l4.237 8.457-3.25 1.635-4.346-8.606-3.464 4.749z"/><path fill="none" d="M0 0h32v32H0z"/></svg>

You can Try it Online!

  • Related