Qt?Quick 模块支持最常见的用户输入类型,包括鼠标和触摸事件、文本输入和按键事件,其他模块为其他类型的用户输入提供支持。
本文介绍了如何处理基本的用户输入。
输入处理程序让 QML 应用程序处理鼠标和触摸事件。 例如,您可以通过将 TapHandler 添加到 Image 或添加到其中包含 Text 对象的 Rectangle 来创建按钮,TapHandler 响应轻敲或点击任何类型的定点设备。
?
class="prettyprint lang-cpp">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 上将焦点设置为 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"
}
}
}
}
?
Qt技术交流群4:166830288??????欢迎一起进群讨论