Search code examples
qtqmlonkeypress

(Q) QML Key Pressed


I want to increase the number when I press any key on the keyboard on QML, it works by making the arrow keys, Keys.onUpPressed: {increment()} but when I want to increase it by pressing the x key, When I try this command Keys.onXPressed: {increment()} it does not happen. and I want it to increase in proportion to the time the key is pressed, how can I control it.

import QtQuick 2.12
import QtQuick.Window 2.12
Window {
  id: root
  visible: true;
  color: "lightgrey"
  width: 500
  height: 500
  Keys.onPressed: {
    switch (event.key) {
      case Qt.Key_Up:
      vueGrille.commencer();
      root.showgrille();
      break;
      case Qt.Key_Down:
      vueGrille.mouveBas();
      root.showgrille();
      break;
      case Qt.Key_Left:
      vueGrille.mouveGauche();
      root.showgrille()
      break;
      case Qt.Key_Right:
      vueGrille.mouveDroite();
      root.showgrille()
      break;
      default:
      break;
    }
  }
  Text {
    id: label1
    font.pixelSize: 30
    property int upPressed: 0
    text: "Key UP Pressed " + upPressed + "Times"
    onTextChanged: console.log("Text Changed to " +text)
    focus: true
    Keys.onUpPressed: {
      increment()
    }
    Keys.onEscapePressed: {
      label1.text = ''
    }
    function increment(){
      upPressed = upPressed + 1
    }
  }
}

Solution

  • There is no Keys.onXPressed handler. You need to check the key in Keys.onPressed.

          Keys.onPressed: {
              if (event.key === Qt.Key_X) {
                increment()
              }
          }