Search code examples
qtqmlqtquick2qtquickcontrols2

Change cursor color in TextField


How do I change the cursor color and probably width in QML TextField element?

Let's say we have the following:

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?


Solution

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