ListView未按预期放置在布局中

时间:2014-03-05 08:27:35

标签: qt qml qt-quick qtquick2 qlayout

我有一个带有RowLayout的ColumnLayout。 RowLayout按预期定位。如果调整窗口大小,也是如此。即使窗口小于整个ColumnLayout(见第二张图片)

但是,如果我用(水平)ListView替换RowLayout,则此ListView不会像我期望的那样定位。我希望它的行为类似于RowLayout的示例,但ListView位于更高的位置:

如果窗口变为'小',则蓝色矩形'移入'ListView,与第一个示例不同:

如何使用ListView实现第一个示例的行为?

来源

import QtQuick 2.0
import QtQuick.Layouts 1.1

Rectangle {
    width: 360
    height: 360

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 20

        Item {
            Layout.fillHeight: true
        }
/*
        ListView {
            Layout.fillHeight: true
            Layout.fillWidth: true
            orientation: ListView.Horizontal
            spacing: 5
            model: 3
            delegate: Rectangle {
                width: 50
                height: 50
                color: "red"
            }
        }
*/

        RowLayout {
            Layout.fillHeight: true
            Layout.fillWidth: true

            Rectangle {
                width: 50
                height: 50
                color: "red"
            }

            Rectangle {
                width: 50
                height: 50
                color: "red"
            }

            Rectangle {
                width: 50
                height: 50
                color: "red"
            }
        }

        Item {
            Layout.fillHeight: true
        }

        Rectangle {
            width: 50
            height: 50
            color: "blue"
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您只需要为ListView定义宽度和高度。这样,您的列布局将考虑其大小并将其保持为固定大小。

此处您的代码已更新:

import QtQuick 2.0
import QtQuick.Layouts 1.1

Rectangle {
    width: 360
    height: 360

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 20

        Item {
            Layout.fillHeight: true
        }

        ListView {
            //take as much width as possible with a binding
            width: parent.width
            //keep enought height to display each delegate instance
            height: 50
            orientation: ListView.Horizontal
            spacing: 5
            model: 3
            delegate: Rectangle {
                width: 50
                height: 50
                color: "red"
            }
        }

        Item {
            Layout.fillHeight: true
        }

        Rectangle {
            width: 50
            height: 50
            color: "blue"
        }
    }
}