如何更改 QML
TextField
元素中的光标颜色和宽度?
假设我们有以下内容:
import QtQuick 2.12
import QtQuick.Controls 2.12
TextField {
id: control
placeholderText: qsTr("Enter description")
background: Rectangle {
implicitWidth: 200
implicitHeight: 40
color: control.enabled ? "transparent" : "#353637"
border.color: control.enabled ? "#21be2b" : "transparent"
}
}
如何使光标颜色为绿色或蓝色或其他颜色?
cursorDelegate
将 矩形 设置为所需的颜色,因为 TextField
继承自 TextInput
,因此共享该属性。
import QtQuick 2.12
import QtQuick.Controls 2.12
TextField {
id: control
placeholderText: qsTr("Enter description")
cursorDelegate: Rectangle {
visible: control.cursorVisible
color: "salmon"
width: control.cursorRectangle.width
}
background: Rectangle {
implicitWidth: 200
implicitHeight: 40
color: control.enabled ? "transparent" : "#353637"
border.color: control.enabled ? "#21be2b" : "transparent"
}
}
定义自定义时,闪烁行为将不会保留
cursorDelegate
。
如果你想要光标闪烁。可以使用动画来完成:
import QtQuick 2.12
import QtQuick.Controls 2.12
TextField {
id: control
placeholderText: qsTr("Enter description")
background: Rectangle {
implicitWidth: 200
implicitHeight: 40
color: control.enabled ? "transparent" : "#353637"
border.color: control.enabled ? "#21be2b" : "transparent"
}
cursorDelegate: Rectangle {
id: cursor
visible: false
color: "salmon"
width: control.cursorRectangle.width
SequentialAnimation {
loops: Animation.Infinite
running: control.cursorVisible
PropertyAction {
target: cursor
property: 'visible'
value: true
}
PauseAnimation {
duration: 600
}
PropertyAction {
target: cursor
property: 'visible'
value: false
}
PauseAnimation {
duration: 600
}
onStopped: {
cursor.visible = false
}
}
}
}