TextInput是用于在用戶界面中輸入文本的控件,通常應用于表單、搜索框等需要用戶輸入文字的場景。以下是對TextInput的詳細解釋,涵蓋其各個方面的功能和屬性。
基本屬性
-
text
- 描述:TextInput中當前顯示的文本。
- 用法:
text: "示例文本"
-
placeholderText
- 描述:當TextInput為空時,顯示的提示文本。
- 用法:
placeholderText: "請輸入內容"
-
readOnly
- 描述:設置TextInput是否為只讀。
- 用法:
readOnly: true
-
echoMode
- 描述:設置TextInput的顯示模式,通常用于密碼輸入時隱藏文本。
- 用法:
echoMode: TextInput.Password
輸入控制
-
inputMethodHints
- 描述:提供輸入法的提示,如僅允許數字輸入。
- 用法:
inputMethodHints: Qt.ImhDigitsOnly
-
validator
- 描述:用于驗證TextInput的輸入是否合法。
- 用法:
validator: RegExpValidator { regExp: /^[0-9]*$/ }
-
maximumLength
- 描述:限制TextInput的最大字符數。
- 用法:
maximumLength: 20
-
focus
- 描述:設置或獲取TextInput的焦點狀態。
- 用法:
focus: true
外觀和樣式
-
font.family
- 描述:設置TextInput中文本的字體。
- 用法:
font.family: "Arial"
-
font.pointSize
- 描述:設置TextInput中文本的字體大小。
- 用法:
font.pointSize: 16
-
color
- 描述:設置TextInput中文本的顏色。
- 用法:
color: "black"
-
selectionColor
- 描述:設置TextInput中選中文本的顏色。
- 用法:
selectionColor: "blue"
交互和行為
-
onTextChanged
- 描述:當TextInput中的文本變化時調用的回調函數。
- 用法:
onTextChanged: { console.log("文本變化: " + text) }
-
onEditingFinished
- 描述:當用戶完成編輯(如按下回車鍵)時調用的回調函數。
- 用法:
onEditingFinished: { console.log("編輯完成: " + text) }
-
inputMethodComposing
- 描述:指示當前是否有未完成的輸入法輸入。
- 用法:
inputMethodComposing: false
示例代碼
import QtQuick 2.15
import QtQuick.Controls 2.15ApplicationWindow {visible: truewidth: 640height: 480title: qsTr("TextInput示例")TextInput {id: textInputwidth: 200height: 40placeholderText: qsTr("請輸入內容")font.family: "Arial"font.pointSize: 16color: "black"selectionColor: "blue"maximumLength: 20inputMethodHints: Qt.ImhDigitsOnlyonTextChanged: {console.log("文本變化: " + text)}onEditingFinished: {console.log("編輯完成: " + text)}}
}
這個示例展示了如何使用TextInput的各種屬性,創建一個帶有提示文本、字符限制、輸入法提示以及回調函數的輸入框。通過這些屬性和方法,開發者可以實現多種多樣的文本輸入需求。