QtQuick StackLayout 中的项目中心对齐问题

问题描述 投票:0回答:1

我在使用 qml 将 QtQuick StackLayout 中的项目居中对齐时遇到问题。据我所知,我正在根据文档正确地做事,但我无法得到我所追求的行为。任何帮助将不胜感激。

我想使用堆栈布局,这样当当前索引处的项目小于布局的最小尺寸时,它不会被拉伸而是位于布局的中心。我了解其机制是

Layout.alignment
附加属性,我将其设置为项目上的
Qt.AlignHCenter | Qt.AlignVCenter
,但这似乎没有效果。该项目保留在左上角。

我还需要堆栈布局具有当前索引处项目的隐式大小,而不是所有项目的最大大小。我认为这是通过覆盖隐式大小属性来实现的。

我在下面的代码片段中得到了我的问题的最小再现。红色矩形应位于

StackLayout
的中心,但它位于左上角。您可以将其粘贴到 qmlonline.kde.org 中以快速渲染场景。

import QtQuick 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls 2.15

ColumnLayout {
    StackLayout {
        id: stack
        
        currentIndex: 0
        implicitWidth: children[currentIndex].implicitWidth
        implicitHeight: children[currentIndex].implicitHeight
        
        Layout.minimumWidth: 400
        Layout.minimumHeight: 250
        Layout.fillWidth: true
        Layout.fillHeight: true
        
        Rectangle {
            color: "red"
            implicitWidth: 100
            implicitHeight: 100
            Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
            Layout.fillHeight: false
            Layout.fillWidth: false
        }
                    
        Rectangle {
            color: "green"
            implicitWidth: 500
            implicitHeight: 300
            Layout.fillHeight: false
            Layout.fillWidth: false
        }
    }
    RowLayout {
        Button {
            text: "Red"
            onClicked: stack.currentIndex = 0
        }
        Button {
            text: "Green"
            onClicked: stack.currentIndex = 1
        }
    }
}
qt qml qtquick2
1个回答
0
投票

您应该让

StackLayout
完全占据您需要的空间,并且您应该将
Item
作为
StackLayout
的子级的顶层,因为知道该项目会自动填充
StackLayout
的内容。之后,将您的项目集中在这些
Item
中就很简单了:

import QtQuick 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls 2.15
Page {
    StackLayout {
        id: stack
        currentIndex: 0
        anchors.fill: parent
        Item {
            Rectangle {
                anchors.centerIn: parent
                color: "red"
                width: 100
                height: 100
            }
        }
        Item {
            Rectangle {
                anchors.centerIn: parent
                color: "green"
                width: 500
                height: 300
            }
        }
    }
    footer: Frame {
        RowLayout {
            Button {
                text: "Red"
                onClicked: stack.currentIndex = 0
            }
            Button {
                text: "Green"
                onClicked: stack.currentIndex = 1
            }
        }
    }
}

您可以在线尝试!

© www.soinside.com 2019 - 2024. All rights reserved.