【问题标题】:ListView inside ColumnLayout inside ScrollView not filling available height/widthScrollView 内的 ColumnLayout 内的 ListView 未填充可用的高度/宽度
【发布时间】:2021-01-25 07:11:22
【问题描述】:

我想在 TextFeild、CheckBoxes 和一些 Button 中显示一些数据,然后显示一个很长的列表。我希望整个页面都是可滚动的,而不仅仅是 ListView。我怎样才能做到这一点?

这是我到现在为止的想法:-

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

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    ScrollView { //comment out this
        anchors.fill: parent //comment out this
        ColumnLayout {
            anchors.fill: parent
            spacing: 5

            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 100
                color: "green"
            }
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 100
                color: "red"
            }

            ListView {
                model : 20
                Layout.fillWidth: true
                Layout.fillHeight: true
                delegate: Frame {
                    Label {
                        text: modelData + "th Item"
                    }
                }

            }
        }
    } //comment out this
}

这不起作用。它只显示 ListView 的一个单元格且不可滚动。如何让 ListView 填充高度/宽度并使整个页面可滚动?

【问题讨论】:

  • 你的目标是让绿色和红色的 Rectangles 与 ListView 一起滚动吗?您可以将它们放在 ListView 的标题中并摆脱 ColumnLayout。
  • @JarMan。是的。这就是我的目标。但是我有另一个 Rectacgle 作为 ListView 的标题 headerPositioning : ListView.PullBackHeader

标签: qt listview qml scrollview


【解决方案1】:

第一个问题是如果ScrollView 的内容与ScrollView 的高度相同,则它无法滚动。它需要内容更大。否则没有什么可以滚动到的。所以适合父母身高的ColumnLayout 是行不通的。在这种情况下,ColumnColumnLayout 更好,因为它会增长到其子级的高度,而不是将其子级调整为自己的大小。

第二个问题是ListView 没有正确计算出它的高度。我不完全确定为什么不这样做,但我能够通过使用 childrenRect.height 让您的示例正常工作。

    ScrollView {
        anchors.fill: parent 
        Column {
            width: parent.width
            spacing: 5

            Rectangle {
                width: parent.width
                height: 100
                color: "green"
            }
            Rectangle {
                width: parent.width
                height: 100
                color: "red"
            }

            ListView {
                model : 20
                width: parent.width
                height: childrenRect.height
                delegate: Frame {
                    Label {
                        text: modelData + "th Item"
                    }
                }

            }
        }
    }

【讨论】: