5

How to change cursor color and probably width in QML TextField element? Let say we have following one:

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

How to make cursor color green or blue or whatever? Thanks!

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Aleksey Kontsevich
  • 4,671
  • 4
  • 46
  • 101

2 Answers2

10

You have to set Rectangle with the color you want as the cursor through the cursorDelegate since TextField inherits from TextInput and therefore shares that property.

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"
    }
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
7

@eyllanesc provides a very good answer, but I want to point that the blinking behavior will not be preserved when you define a custom cursorDelegate.

If you want to have the blinking of the cursor. It can be done using an animation:

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
            }
        }
    }
}
Nicolas Dusart
  • 1,867
  • 18
  • 26