Search code examples
qtqml

How to align Button's text


I have a button with some text which is normally centered, but I want this text to align to the left. I have tried some things, but they don't seem to work. Is this possible? If yes, how can it be done?

import QtQuick 2.15
import QtQuick.Window 2.2
import QtQuick.Controls 2.15

Window {
    id: window
    visible: true
    height: 400
    width: 400

    Button {
        id: button
        text: "Align me to the left"
        //horizontalAlignment: Text.AlignLeft
        width: parent.width
        height: 30
        flat: true
        onClicked: {
            console.log("You clicked me")
        }
    }
}

Solution

  • To customize a Button, you can override the contentItem and/or background properties. If you want left-aligned text, just use the contentItem to create a Text object that looks the way you want it.

    Button {
        contentItem: Text {
            text: parent.text
            font: parent.font
            horizontalAlignment : Text.AlignLeft
        }
    
        ...
    }