Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML: Change cursor color in TextField

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!

like image 211
Aleksey Kontsevich Avatar asked Dec 23 '22 20:12

Aleksey Kontsevich


2 Answers

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"
    }
}
like image 150
eyllanesc Avatar answered Dec 28 '22 07:12

eyllanesc


@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
            }
        }
    }
}
like image 20
Nicolas Dusart Avatar answered Dec 28 '22 08:12

Nicolas Dusart