qtqmlqtquickcontrols2

Textfield with an icon and placeholder text


is there a way to get a textfield to display the placeholder text next to an icon like in the picture below.

I tried doing it by setting the padding, but that only works for the actual text not the placeholder text.

import QtQuick
import QtQuick.Controls

TextField {
    property alias iconSource: image.source

    selectByMouse: true
    leftPadding: iconSource.toString() ? 32 : 16

    Image {
        id: image
        anchors.verticalCenter: parent.verticalCenter
        width: parent.height * 0.5
        height: width
        sourceSize.width: width
        sourceSize.height: height
    }
}

It looks ok if the textfield is focused. If it is out of focus, the text is overlapped by the icon (see password field):

enter image description here

But I want it to look like this:

enter image description here


Solution

  • The TextField in Material style uses Material.textFieldHorizontalPadding (source code). And since textFieldHorizontalPadding is read-only and there is no alias defined for placeholder, you cannot change the placeholder's x position directly.

    There are two options here:

    Note
    There are also some issues if you want to use it with RTL, which you can fix by adding some conditions.