0
votes

How to center element inside qml ColumnLayout? I unsuccessfully tried:

Layout.alignment: Qt.AlignCenter

code:

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Layouts 1.11
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    ColumnLayout{
        anchors.centerIn: parent
        width: parent.width
        Layout.preferredHeight:  parent.height
        visible: true

        Text{
            id: myText
            text: "My Text"
            Layout.preferredWidth: parent.width
            Layout.preferredHeight: 25
            Layout.alignment: Qt.AlignCenter
        }
    }
}

But myText is still not horizontally centered. Any idea?

enter image description here

1

1 Answers

2
votes

If we review with the Quick Designer we obtain the following:

enter image description here

As we see the item is centered. The problem is that Layout does not handle the position of the text inside the Text item, for this you must use horizontalAlignment:

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Layouts 1.11
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    ColumnLayout{
        anchors.centerIn: parent
        width: parent.width
        Layout.preferredHeight:  parent.height
        visible: true

        Text{
            id: myText
            text: "My Text"
            Layout.preferredWidth: parent.width
            Layout.preferredHeight: 25
            horizontalAlignment: Text.AlignHCenter
        }
    }
}

enter image description here