Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

mouse.button with switch-case



  • Hi, I tried to use switch-case with mouse.button but, it seems that doesn't work.

    I want to know the reason.

    Why It doesn't work?

    MouseArea {
        anchors.fill: parent
        acceptedButtons: Qt.AllButtons
        // ...
        onPressed: {
            property string buttonID = 'Nothing'
    
            switch (mouse.button) {
            case Qt.LeftButton: buttonID = 'LeftButton'; break;
            case Qt.RIghtButton: buttonID = 'RIghtButton'; break;
            }
            test.text = 'pressed ' + buttonID
        }
    }
    

    I found it works whether I use if-else not switch-case.

    I can not understand what is the difference between two of them.

    Please, Let me know.

    Thank you! :)

    ps. I missed something like 'break' or 'acceptedButtons' ... but it were there when I found the problem, and I edited them. sorry.

    I am really sorry, It turned out my fault.
    I wrote wrong spell " switch (mouse.botton) { ..."
    now it works.
    Thanks all your comments.



  • hi,
    @hslee_6560 said in mouse.button with switch-case:

    onPressed: {
    property string buttonID = 'Nothing'

    you can not write QML inside js block

    declare your buttonID like you declare js variable , not QML property

      onPressed: {
            var buttonID = 'Nothing'
    


  • Beside of a lot of syntax mistakes you are using switch in a wrong way. Add break at the end of each case block.



  • @hslee_6560 said in mouse.button with switch-case:

    switch (mouse.button) {
    case Qt.LeftButton: buttonID = 'LeftButton'
    case Qt.RIghtButton: buttonID = 'RIghtButton'
    }

    The acceptedButtons value for MouseArea is Qt.LeftButton

    To indicate that all possible mouse buttons are to be accepted, the special value 'Qt.AllButtons' may be used.
    Refer: acceptedButtons : Qt::MouseButtons.

    MouseArea { acceptedButtons: Qt.AllButtons }
    

    Please check for the Spelling & Syntax

        MouseArea {
            property string buttonID: 'Nothing'
    
            anchors.fill: parent
            acceptedButtons: Qt.AllButtons
    
            onClicked: {
                switch (mouse.button) {
                case Qt.LeftButton: buttonID = 'LeftButton'
                    break;
                case Qt.RightButton: buttonID = 'RightButton'
                    break;
                }
    
                textEdit.text = 'pressed ' + buttonID;
            }
        }
    

    All the best.



  • hi,
    @hslee_6560 said in mouse.button with switch-case:

    onPressed: {
    property string buttonID = 'Nothing'

    you can not write QML inside js block

    declare your buttonID like you declare js variable , not QML property

      onPressed: {
            var buttonID = 'Nothing'
    

Log in to reply