具有多个嵌套模型的 QML ListView 高度

QML ListView height with multiple nested models

我有一个带有简单模型的 ListView,它也有一个实际显示的模型:

ListView {
    Component.onCompleted: console.log("ListView height: " + height)
    model: ["1"]
    delegate: Column {
        Component.onCompleted: console.log("Inner delegate height: " + height)
        Repeater {
            model: ["A", "B"]
            delegate: Text {
                Component.onCompleted: console.log("Text height: " + height)
                text: modelData
            }
        }
    }
}

我可以得到 TextColumn 高度。即使 ListModel 知道 Column 高度,它的高度仍然为零。

我的问题是:如何正确分配 ListView 给定的大小?

程序输出:

qml: Text height: 14
qml: Text height: 14
qml: Inner delegate height: 28
qml: ListView height: 0

根据@folibis 的建议,我在委托的 heightwidth 更改时更改了 contentHeightcontentWidth 属性。将anchors添加到ListView后,它与包含的项目完美配合。

代码如下:

ListView {
    anchors.fill: parent
    model: ["1", "2"]
    delegate: Column {
        onHeightChanged: ListView.view.contentHeight = height
        onWidthChanged: ListView.view.contentWidth = width
        Repeater {
            model: ["A", "B", "C", "D"]
            delegate: Text {
                text: modelData
            }
        }
    }
}

受@BaCaRoZzo 的评论启发,如果不需要 ListView,没有它也可以解决问题:

Flickable {
    id: flickable
    anchors.fill: parent
    Column {
        Repeater {
            model: ["1", "2"]
            Column {
                onHeightChanged: flickable.contentHeight = height
                onWidthChanged: flickable.contentWidth = width
                Repeater {
                    model: ["A", "B", "C", "D"]
                    delegate: Text {
                        text: modelData
                    }
                }
            }
        }
    }
}