首页 > 解决方案 > qml ColumnLayout内的中心元素

问题描述

如何在qml ColumnLayout中居中元素?我尝试失败:

Layout.alignment: Qt.AlignCenter

代码:

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

但是 myText 仍然不是水平居中的。任何想法?

在此处输入图像描述

标签: qtqmlqt5

解决方案


如果我们使用快速设计器进行审查,我们会获得以下信息:

在此处输入图像描述

正如我们所见,该项目居中。问题是 Layout 不处理文本项内文本的位置,为此您必须使用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
        }
    }
}

在此处输入图像描述


推荐阅读