Search code examples
qmlmouseevent

Retrieving the used modifiers on button click with QtQuick 2.9


I've got that pure QML application working on QtQuick 2.9.

I'm trying to retrieve the keyboard modifier used during the mouseclick.

From QtQuick 2.15, I could write this:

Button {
    text: "button"
    onClicked: {
        if ((mouse.button == Qt.LeftButton) && (mouse.modifiers & Qt.ShiftModifier)) {
            doSomething();
    } else {
            doSomethingElse();
        }
    }
}

But the MouseEvent isn't available in QtQuick 2.9.

What's the alternative ?


Solution

  • A Button's clicked signal does not provide a MouseEvent (no matter what version of Qt you're using). The clicked signal could be generated via the keyboard too, so it wouldn't make sense to provide a MouseEvent. You will need to create a MouseArea and handle the events yourself to do what you want.

    Button {
        id: button
    
        MouseArea {
            id: mouse
            anchors.fill: parent
    
            onPressed: {
                if ((mouse.button == Qt.LeftButton) && (mouse.modifiers & Qt.ShiftModifier)) {
                    doSomething();
                } else {
                    doSomethingElse();
                }
            }
        }
    }