我们已经使用过MouseArea(鼠标区域)作为鼠标输入元素。这里我们将更多的介绍关于键盘输入的一些东西。我们开始介绍文本编辑的元素:TextInput(文本输入)和TextEdit(文本编辑)。
7.1 TextInput(文本输入)
文本输入允许用户输入一行文本。这个元素支持使用正则表达式验证器来限制输入和输入掩码的模式设置。
import QtQuick 2.15import QtQuick.Window 2.15Rectangle {width: 200height: 100TextInput {id: input1x: 8; y: 8width: 96; height: 25text: "Text Input 1"}TextInput{id: input2x: 8; y: 36width: 96; height: 20text: "Text Input 2"}TextInput {id: input3x: 8; y: 64validator: IntValidator{bottom: 11; top: 31;} // 输入范围 [11,13]width: 96; height: 20}}
设置按键向导,按tab键可以切换光标的位置
import QtQuick 2.15import QtQuick.Window 2.15Rectangle {width: 200height: 100TextInput {id: input1x: 8; y: 8width: 96; height: 25text: "Text Input 1"KeyNavigation.tab: input2 // 按键向导}TextInput{id: input2x: 8; y: 36width: 96; height: 20text: "Text Input 2"KeyNavigation.tab: input3}TextInput {id: input3x: 8; y: 64validator: IntValidator{bottom: 11; top: 31;}width: 96; height: 20KeyNavigation.tab: input1}}
TextInput增加矩形框,以便用户鉴别这是一个输入元素(如果文本过长,前面的文本会跑到边框的签名)

import QtQuick 2.15FocusScope {width: 96; height: 96Rectangle {anchors.fill: parentcolor: "lightsteelblue"border.color: "gray"}property alias text: input.textproperty alias input: inputTextEdit {id: inputanchors.fill: parentanchors.margins: 4focus: true}}
import QtQuick 2.15import QtQuick.Window 2.15Rectangle {width: 136height: 120color: "linen"TTextEdit {id: inputx: 8; y: 8width: 120; height: 104focus: truetext: "Text Edit"}}
7.4 按键元素(Key Element)
附加属性key允许你基于某个按键的点击来执行代码。例如使用up,down按键来移动一个方块,left,right按键来旋转一个元素,plus,minus按键来缩放一个元素。
import QtQuick 2.15import QtQuick.Window 2.15Rectangle {width: 400; height: 200Rectangle {color: "red"id: squarex: 8; y: 8width: 45height: 45border.color: Qt.lighter(color)}focus: trueKeys.onLeftPressed: square.x -= 8Keys.onRightPressed: square.x += 8Keys.onUpPressed: square.y -= 8Keys.onDownPressed: square.y += 8Keys.onPressed: {switch(event.key) {case Qt.Key_Plus:square.scale += 0.2break;case Qt.Key_Minus:square.scale -= 0.2break;}}}

