【问题标题】:QML: Change cursor color in TextFieldQML:更改文本字段中的光标颜色
【发布时间】:2019-11-05 21:33:51
【问题描述】:

如何在 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"
    }
}

如何使光标颜色为绿色或蓝色或其他?谢谢!

【问题讨论】:

    标签: qt qml qt5 qtquick2 qtquickcontrols2


    【解决方案1】:

    由于TextField 继承自TextInput 并因此共享该属性,因此您必须通过cursorDelegate 将矩形设置为您想要的颜色作为光标。

    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"
        }
    }

    【讨论】:

    • 呃,在文档中错过了。非常感谢!工作就好了!
    【解决方案2】:

    @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
                }
            }
        }
    }
    

    【讨论】:

    • 对!很好的补充,谢谢!
    猜你喜欢
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2022-08-19
    相关资源
    最近更新 更多