Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML- Right Click Not Detected in MouseArea

Tags:

qt

qml

qtquick2

I'm working on an image editor and specifically working on setting the current left or right button's associated color using a MouseArea (inside a Button type). The problem I'm having is that I can't seem to filter for particular buttons at all. Here's the snippet giving me trouble:

    Button {
        x: 60
        width: 80
        height: 40
        text: "Blue"

        anchors.verticalCenter: parent.verticalCenter

        onButtonClick: {
            if(mouseArea.pressedButtons & Qt.RightButton) {
                console.log("Right button used");
                GlobalState.setRightColorValues(0.0, 0.0, 1.0, 1.0);
            } else {
                console.log("Left button used");
                GlobalState.setLeftColorValues(0.0, 0.0, 1.0, 1.0);
            }
        }
    }

(If needed I can provide the entirety of Button.qml, but it's mostly from here).

I'm trying to follow the example here, but the method used to filter for right mouse clicks doesn't seem to work (anymore, anyway). What happens is the statement "defaults" to assuming a left click. I've also tried separating the two into different if-statements, but doing so causes no buttons to be filtered explicitly.

What needs to be changed in order to filter for specific mouse buttons? Or will I have to implement the sort of "switch primary color" button used in Paint/Paint.NET?

Edit 1: I've realized that there was a relevant snippet missing from Button.qml-

 MouseArea{
    id: buttonMouseArea;

    acceptedButtons: Qt.AllButtons;
    hoverEnabled: true

    onEntered: parent.color = onHoverColor
    onExited:  parent.color = buttonColor

    anchors.fill: parent;

    onClicked: buttonClick();
}

This is nested inside a Rectangle, which also holds a Text field.

like image 750
Cave Dweller Avatar asked Mar 16 '14 22:03

Cave Dweller


1 Answers

By default MouseArea only handles the left mouse button. You can handle other buttons by setting the acceptedButtons property. You can determine which button caused the click by using the mouse MouseEvent that is accessible in the onClicked handler.

MouseArea {
    acceptedButtons: Qt.LeftButton | Qt.RightButton

    onClicked: {
        if (mouse.button === Qt.RightButton) { // 'mouse' is a MouseEvent argument passed into the onClicked signal handler
            console.log("right button clicked!")
        } else if (mouse.button === Qt.LeftButton) {
            console.log("left button clicked!")
        }
    }
}

See acceptedButtons, and mouse MouseEvent

like image 138
MartinJ Avatar answered Oct 05 '22 22:10

MartinJ