Search code examples
qtqmlqt5qtquick2mouse-cursor

How to change cursor shape in qml when MouseArea is covered with another MouseArea


There are two MouseAreas with two different responsibilities and one (green) is positioned partially on top of the other (red). I would like to change cursor's shape whenever red MA is hovered (even if it is under the green MA), and I would like green MA to react to press and nothing else.

Two MA's could be in different files so I don't want to make explicit dependencies between them like setting proper cursorShape in green whenever containsMouse in red changes. Is there a way to prevent the green MouseArea from handling cursor shape?

import QtQuick 2.4
import QtQuick.Window 2.2

Window {
    visible: true
    width: 200
    height: 200

    Rectangle { anchors.fill: parent; color: "yellow"; }

    MouseArea {
        width: 150
        height: 150
        hoverEnabled: true
        cursorShape: Qt.OpenHandCursor
        Rectangle { anchors.fill: parent; color: "red"; }
        onPositionChanged: console.log("position", mouse.x, mouse.y)
        onContainsMouseChanged: console.log("containsMouse", containsMouse)
    }
    MouseArea {
        x: 50
        y: 50
        width: 150
        height: 150
        hoverEnabled: false
        Rectangle { anchors.fill: parent; color: "green"; }
        onPressed: console.log("Ahoj!")
    }
}

Solution

  • There is no way to do this by MouseArea properties or any other ready solution. MouseArea always sets some cursor shape -- if cursorShape property is not specified than the default value is used (Qt.ArrowCursor) You can of course use mapToItem()/mapFromItem() to workaround this problem (as Mitch suggested). But there are other possibilities too:

    You can temporary change visible to false of overlaying mouse area.
    Alternatively if both MouseArea are siblings, you can operate on z property to obtain specific hierarchy of object suitable for your needs.