Use Case - Responding To User Input in QML
Supported Types of User Input
The Qt Quick module provides support for the most common types of user input, including mouse and touch events, text input and key-press events. Other modules provide support for other types of user input (for example, the Qt Sensors module provides support for shake-gestures in QML applications).
This article covers how to handle basic user input; for further information about motion-gesture support, please see the Qt Sensors documentation. For information about audio-visual input, please see the Qt Multimedia documentation.
Mouse and Touch Events
The MouseArea type allows mouse and touch events to be handled in a QML application. A MouseArea can be combined with either an Image or a Rectangle and Text object to implement a simple button.
import QtQuick 2.3 Item { id: root width: 320 height: 480 Rectangle { color: "#272822" width: 320 height: 480 } Rectangle { id: rectangle x: 40 y: 20 width: 120 height: 120 color: "red" MouseArea { anchors.fill: parent onClicked: rectangle.width += 10 } } }
For more advanced use cases requiring multiple touch points, please read the documentation for the MultiPointTouchArea type and the PinchArea type.
Note that some types have their own built in input handling. For example, Flickable responds to mouse dragging, mouse wheel scrolling, touch dragging, and touch flicking by default.
Keyboard and Button Events
Button and key presses, from buttons on a device, a keypad, or a keyboard, can all be handled using the Keys attached property. This attached property is available on all Item derived types, and works with the Item::focus property to determine which type receives the key event. For simple key handling, you can set the focus to true on a single Item and do all your key handling there.
import QtQuick 2.3 Item { id: root width: 320 height: 480 Rectangle { color: "#272822" width: 320 height: 480 } Rectangle { id: rectangle x: 40 y: 20 width: 120 height: 120 color: "red" focus: true Keys.onUpPressed: rectangle.y -= 10 Keys.onDownPressed: rectangle.y += 10 Keys.onLeftPressed: rectangle.x += 10 Keys.onRightPressed: rectangle.x -= 10 } }
For text input the Qt Quick module provides several built-in types. In particular, the TextInput and TextEdit types allow for single-line entry and multi-line editing respectively.
Here is all you need to get a working TextInput:
import QtQuick 2.3 TextInput { focus: true text: "Initial Text" }
© 2017 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.