QML入门教程:八、输入元素

1、文本输入
文本输入允许用户输入一行文本。这个元素支持使用正则表达式验证器来限制输入和输入掩码的模式设置。

// textinput.qml
import QtQuick 2.0
Rectangle {
width: 200
height: 80
color: "linen"
TextInput {
id: input1
x: 8; y: 8
width: 96; height: 20
focus: true
text: "Text Input 1"
}  
TextInput {
id: input2
x: 8; y: 36
width: 96; height: 20
text: "Text Input 2"
}
}

用户可以通过点击TextInput来改变焦点。为了支持键盘改变焦点,我们可以使用
KeyNavigation(按键向导) 这个附加属性

// textinput2.qml
import QtQuick 2.0
Rectangle {
width: 200
height: 80
color: "linen"
TextInput {
id: input1
x: 8; y: 8
width: 96; height: 20
focus: true
text: "Text Input 1"
KeyNavigation.tab: input2
}   
TextInput {
id: input2
x: 8; y: 36
width: 96; height: 20
text: "Text Input 2"
KeyNavigation.tab: input1
}
}

KeyNavigation(按键向导) 附加属性可以预先设置一个元素id绑定切换焦点的按
键,如上述代码input1和input2被点击时互相切换焦点。
一个文本输入元素(text input element) 只显示一个闪烁符和已经输入的文本。用
户需要一些可见的修饰来鉴别这是一个输入元素,例如一个简单的矩形框。当你放
置一个TextInput(文本输入) 在一个元素中时,你需要确保其它的元素能够访问它
导出的大多数属性。
提取代码作为组件:

// TLineEditV1.qml
import QtQuick 2.0
Rectangle {
width: 96; height: input.height + 8
color: "lightsteelblue"
border.color: "gray"
property alias text: input.text
property alias input: input
TextInput {
id: input
anchors.fill: parent
anchors.margins: 4
focus: true
}
}

如果想要完整的导出TextInput元素,可以使用property alias input: input
导出这个元素。第一个input是属性名字,第二个input是元素id。

2、焦点区域(FocusScope)
一个焦点区域(focus scope) 定义了如果焦点区域接收到焦点,它的最后一个使用
focus:true的子元素接收焦点,它将会把焦点传递给最后申请焦点的子元素。

// TLineEditV2.qml
import QtQuick 2.0
FocusScope {
width: 96; height: input.height + 8
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: 4
focus: true
}
}

3、文本编辑(TextEdit)
文本编辑(TextEdit) 元素与文本输入(TextInput) 非常类似,它支持多行文本编
辑。它不再支持文本输入的限制,但是提供了已绘制文本的大小查询

// TTextEdit.qml
import QtQuick 2.0
FocusScope {
width: 96; height: 96
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: 4
focus: true
}
}

4、按键元素 (Key Element)
附加属性key允许你基于某个按键的点击来执行代码。例如使用up,down按键来移
动一个方块,left,right按键来旋转一个元素,plus,minus按键来缩放一个元素。

// keys.qml
import QtQuick 2.0
DarkSquare {
width: 400; height: 200
GreenSquare {
id: square
x: 8; y: 8
} f
ocus: true
Keys.onLeftPressed: square.x -= 8
Keys.onRightPressed: square.x += 8
Keys.onUpPressed: square.y -= 8
Keys.onDownPressed: square.y += 8
Keys.onPressed: {
switch(event.key) {
case Qt.Key_Plus:
square.scale += 0.2
break;
case Qt.Key_Minus:
square.scale -= 0.2
break;
}
}
}

QML入门教程源码(1-8):
链接:https://pan.baidu.com/s/1mGuIok31-00odlJGDUVM3g 密码:mfuk

你可能感兴趣的:(QML,QT,Qt,QML)