5

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

但是,如果我将 RowLayout 替换为(水平)ListView,则此 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"
        }
    }
}
4

1 回答 1

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"
        }
    }
}
于 2014-03-05T11:47:41.480 回答