ListView 未按预期定位在布局中

avb*_*avb 5 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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

eps*_*lon 3

您只需要定义 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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这适用于这个特定的例子。但是如果代表的高度是动态的怎么办?ListView 高度的硬编码值无法正常工作...那是因为我尝试了 Layout.fillHeight: true (5认同)