概念
TextInput用来显示单行可编辑的文本。类似于QLineEdit
可以设置validator和inputMask。
1. 验证器和掩码
验证器:
Item{
width: 100
height: 50
TextInput{
validator: IntValidator{bottom: 11; top: 31}
focus: true
onEditingFinished: console.log(text)
}
}
掩码:
按下回车键会调用onEditingFinished
信号处理器,而且只有当所以必须输入的字符都输入后,按下回车键才可以调用该信号处理器。
Item{
Rectangle{
id: rect
width: input.contentWidth < 100 ? 100 : input.contentWidth + 10
height: input.contentHeight + 5
color: "lightgrey"
border.color: "grey"
TextInput{
id: input
anchors.fill: parent
anchors.margins: 2
font.pointSize: 15
focus: true
inputMask: ">AA_9_a"
onEditingFinished: text2.text = text
}
Text {
id: text2
anchors.top: rect.bottom
}
}
}
2. 回显方式
echoMode
TextInput.Normal
- 直接显示文本(默认)
TextInput.Password
- 使用密码掩码字符(根据不同平台显示不同的效果)来代替真实的字符。
TextInput.NoEcho
- 不显式输入的内容
TextInput.PasswordEchoOnEdit
- 使用密码掩码字符,但在输入时显示真实字符。
import QtQuick
Item {
width: 100
height: 50
TextInput{
id: textInput
echoMode: TextInput.PasswordEchoOnEdit
focus: true
onAccepted: {textInput.focus = false}
}
}
3. 信号处理器
TextInput提供了两个完成输入的信号处理器:
onAccepted()
、onEditingFinished()
,它们都会在回车键按下时被调用。
区别是,后者在TextInput
失去焦点时也会被调用。
TextInput还提供了一个onTextEdited()
信号,每当内容被编辑时都会调用它,但是通过代码对TextInput
内容进行更改时不会调用该处理器。
import QtQuick
Rectangle{
width: 200
height: 100
TextInput{
id: textInput
focus: true
onTextEdited: console.log(text)
}
MouseArea{
anchors.fill: parent
onClicked: textInput.text = "hello"
}
}
4. 文本选取
设置selectByMouse
属性可以使用鼠标选取TextInpu中的文本。在Qt 6.4以前该属性默认为false,之后的版本默认为true。
在代码中,可以使用selectedText
获取选中的文本,使用selectColor
和selectedTextColor
分别设置选取文本的背景色和前景色。
使用selectionStart
和startEnd
可以分别获取鼠标选取的文本块前后的光标位置。
TextInput还提供了许多和文本选取有关的方法,例如用于复制的copy()
操作。
方法 | 描述 |
---|---|
clear() | 清空内容 |
copy() | 复制当前选取的文本到系统剪贴板 |
cut() | 移动当前选取的文本到系统剪贴板 |
deselect() | 移除当前高亮选择 |
string getText(int start, int end) | 返回在start和end之间的文本 |
insert(int position, string text) | 在position处插入text文本 |
redo() | 重做上一步操作 |
undo() | 撤销上一步操作 |
remove(int start, int end) | 移除在start和end之间选取的文本 |
select(int start, int end) | 选取在start和end之间的文本 |
selectAll() | 全选所有文本 |
selectWord() | 选中光标附近的单词 |
还有一个mouseSelectionMode
属性用来指定鼠标选取文本的方式,其可选值为:
TextInput.SelectCharacters
- 以字符为单位进行选取(默认)。
TextInput.SelectWords
- 以单词为单位进行选取。
例子:
Rectangle{
width: 200
height: 100
TextInput{
text: "hello Qt!"
selectByMouse: true
mouseSelectionMode: TextInput.SelectWords
selectedTextColor: "green"
onAccepted:{
console.log(selectedText.toString())
console.log(selectionStart)
console.log(selectionEnd)
cut()
}
}
}
5. 设置外观
TextInput默认没有漂亮的外观。一般吧直接使用TextInput本事,而是自定义一个组件爱你,外部直接使用新的组件代替TextInput。
NewTextInput.qml
import QtQuick
Rectangle{
property alias text: input.text
property alias input: input
width: input.contentWidth < 100? 100 : input.contentWidth + 10
height: input.contentHeight + 10
color: "#EAEEF1"
border.color: "#D3BBBB"
TextInput{
id: input
anchors.fill: parent
anchors.margins: 5
focus: true
}
}
main.qml
import QtQuick
Item {
width: 200
height: 100
NewTextInput{
x: 50
y: 50
text: "www.bing.com"
}
}