系列文章目录
前言
一、概述
1.1 Textlnput
- 允许用户输入一行文本。元素支持输入约束,如validator、inputMask、echoMod
- 可以在文本输入中单击以更改焦点。使用KeyNavigation属性可以通过键盘更改焦点
1.2 TextEdit
- TextEdit与Textlnput非常相似,支持多行文本编辑字段。它没有文本约束属性,因为这取决于查询文本的内容大小(contentHeight、contentWidth)。我们还创建了自己的名为TTextEdit的组件,以提供编辑背景,并使用焦点范围进行更好的焦点转发。
1.3 Keys
允许基于某些按键执行代码。例如,要移动和缩放一个正方形,我们可以使用上、下、左和右键来平移元素,使用加号和减号键来缩放元素。
二、实例演示
示例1:
import QtQuick 2.9
import QtQuick.Window 2.3
Window {
visible: true
width: 640
height: 480
title: qsTr("Input")
Rectangle {
width: 800;height: 600
color: 'linen'
TextInput {
id: input1
x: 50;y: 50
width: 100;height: 50
focus: true
text: 'Text input 1'
KeyNavigation.tab: input2
}
TextInput {
id: input2
x: 50;y: 100
width: 100;height: 50
// focus: true
text: 'Text input 2'
KeyNavigation.tab: input1
}
}
}
运行结果:
示例2:
TLineEditV1.qml
import QtQuick 2.0
## 不能获取焦点的错误示例
//Rectangle {
// width: 800;height: 600
// color: 'lightsteelblue'
// border.color: 'gray'
// property alias text: input.text
// property alias input: input
// TextInput {
// id: input
// anchors.fill: parent
// anchors.margins: 10
// }
//}
FocusScope {
width: 800;height: 600
Rectangle {
anchors.fill: parent
color: 'lightsteelblue'
border.color: 'gray'
}
property alias text: input.text
property alias input: input
TextInput {
id: input
anchors.fill: parent
anchors.margins: 10
focus: true
}
}
TLineEditV1 {
id: input1
text: "Text input 1"
input.font.pixelSize: 80
height: input.font.pixelSize + 30
input.color: 'white'
focus: true
KeyNavigation.tab: input2
}
TLineEditV1 {
id: input2
y: input1.y + input1.height + 20
text: "Text input 2"
input.font.pixelSize: 80
height: input.font.pixelSize + 30
input.color: 'white'
focus: true
KeyNavigation.tab: input1
}
运行结果:
示例2:
11_chapter2-11Input.qml
#修改多行编辑示例
TLineEditV1 {
id: input1
text: "Text input 1"
input.font.pixelSize: 80
height: 5 * input.font.pixelSize + 30
input.color: 'white'
focus: true
KeyNavigation.tab: input2
}
TLineEditV1.qml
#添加自动换行属性
FocusScope {
width: 800;height: 600
Rectangle {
anchors.fill: parent
color: 'lightsteelblue'
border.color: 'gray'
}
property alias text: input.text
property alias input: input
TextEdit {
id: input
anchors.fill: parent
anchors.margins: 10
focus: true
wrapMode: Text.WordWrap
}
}
运行结果:
示例3:
chapter2-12Keys.qml
import QtQuick 2.9
import QtQuick.Window 2.3
Rectangle {
width: 1000; height: 600
Rectangle {
id: square
width: 200; height: 200
color: 'green'
border.color: Qt.lighter(color)
}
focus: true
Keys.onLeftPressed: square.x -= 20
Keys.onRightPressed: square.x += 20
Keys.onUpPressed: square.y -= 20
Keys.onDownPressed: square.y += 20
Keys.onPressed: function (event) {
switch(event.key) {
case Qt.Key_Plus: square.scale += 0.2; break;
case Qt.Key_Minus: square.scale -= 0.2; break;
}
}
}
运行结果: