Search code examples
qtinputkeyboardqmlmouse

Check if the mouse and spacebar are pressed at the same time in QML


I'd like to check whether or not the mouse and the spacebar keys are being pressed at the same time using QML

I can check if the mouse and other modifier keys are being pressed. For instance:

MouseArea {
  onPressed: {
    if(mouse.modifiers & QT.ControlModifier) {
      // do something
    }
  }
}

However, the only way I know how to check for keys is inside of the Keys.onPressed handlers. Is there a way to communicate between the MouseArea onPressed and Keys.onPressed in unison?


Solution

  • Here is example code of the same issue:

    MyItem.qml

    import QtQuick 2.12
    
    Rectangle {
        id: element
        width: 100
        height: 100
        color: "orange"
        signal mySignal()
        property int myState: MyItem.Bits.None
        enum Bits {
            None = 0,
            MouseOn = 1,
            KeyOn = 2,
            AllOn = 3
        }
    
        function checkBits()
        {
            if(element.myState === MyItem.Bits.AllOn)
            {
                element.mySignal();
                element.myState = MyItem.Bits.None;
            }
        }
    
        MouseArea {
            anchors.fill: parent
            onPressed: {
                element.myState |= MyItem.Bits.MouseOn;
                element.checkBits();
            }
            onReleased: {
                element.myState &= ~MyItem.Bits.MouseOn;
                element.checkBits();
            }
        }
        Keys.onSpacePressed: {
            element.myState |= MyItem.Bits.KeyOn;
            element.checkBits();
        }
        Keys.onReleased: {
            if(element.myState & MyItem.Bits.KeyOn)
            {
                element.myState &= ~MyItem.Bits.KeyOn;
                element.checkBits();
            }
        }
    }
    

    main.qml

    import QtQuick 2.12
    import QtQuick.Window 2.12
    
    Window {
        visible: true
        width: 600
        height: 400
    
        MyItem {
            anchors.centerIn: parent
            focus: true
            onMySignal: {
                console.log("My Signal")
            }
        }
    }
    

    MySignal will be fired on simultaneously Mouse and Space clicking.
    Note, enum requires Qt 5.10 or higher