QML:更改文本字段中的光标颜色

QML: Change cursor color in TextField

如何在 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 since TextField inherits from TextInput 将矩形设置为您想要的颜色作为光标,因此共享 属性。

import QtQuick 2.12
import QtQuick.Controls 2.12

TextField {
    id: control
    placeholderText: qsTr("Enter description")
    <b>cursorDelegate: Rectangle {
        visible: control.cursorVisible
        color: "salmon"
        width: control.cursorRectangle.width
    }</b>
    background: Rectangle {
        implicitWidth: 200
        implicitHeight: 40
        color: control.enabled ? "transparent" : "#353637"
        border.color: control.enabled ? "#21be2b" : "transparent"
    }
}

@eyllanesc 提供了一个很好的答案,但我想指出的是,当您定义自定义 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
            }
        }
    }
}