处理用户输入
支持的用户输入类型
该 Qt Quick 模块支持最常见的用户输入类型,包括鼠标和触摸事件、文本输入以及按键事件。其他模块则支持其他类型的用户输入。
本文介绍了如何处理基本的用户输入。有关视听输入的信息,请参阅 Qt Multimedia 文档。
鼠标和触摸事件
输入处理程序使 QML 应用程序能够处理鼠标和触摸事件。例如,您可以通过将 `TapHandler ` 添加到 `Image` 控件,或添加到内部包含 `Text ` 对象的 `Rectangle ` 控件中,来创建一个按钮。`TapHandler ` 控件可响应任何类型指针设备上的轻触或点击。
import QtQuick
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"
TapHandler {
onTapped: rectangle.width += 10
}
}
}注意:某些控 件类型具有自己的内置输入处理机制。例如,Flickable 控件会响应鼠标拖动、触摸轻扫以及鼠标滚轮滚动。
键盘和按钮事件
来自设备按钮、数字小键盘或键盘的按键和按钮按下事件,均可通过Keys 附加属性进行处理。该附加属性适用于所有继承自Item 的类型,并配合Item::focus 属性共同确定哪个类型接收该按键事件。对于简单的按键处理,您可以将单个Item 的focus属性设置为true,并在该控件中完成所有按键处理。
import QtQuick
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
}
}对于文本输入,有几种 QML 类型可供选择。TextInput 提供无样式的一行可编辑文本,而TextField 更适合应用程序中的表单字段。TextEdit 可以处理多行可编辑文本,但TextArea 是一个更好的选择,因为它增加了样式。
以下代码片段演示了如何在应用程序中使用这些类型:
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
ApplicationWindow {
width: 300
height: 200
visible: true
ColumnLayout {
anchors.fill: parent
TextField {
id: singleline
text: "Initial Text"
Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
Layout.margins: 5
background: Rectangle {
implicitWidth: 200
implicitHeight: 40
border.color: singleline.focus ? "#21be2b" : "lightgray"
color: singleline.focus ? "lightgray" : "transparent"
}
}
TextArea {
id: multiline
placeholderText: "Initial text\n...\n...\n"
Layout.alignment: Qt.AlignLeft
Layout.fillWidth: true
Layout.fillHeight: true
Layout.margins: 5
background: Rectangle {
implicitWidth: 200
implicitHeight: 100
border.color: multiline.focus ? "#21be2b" : "lightgray"
color: multiline.focus ? "lightgray" : "transparent"
}
}
}
}© 2026 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.