如何通知QtQuick2 TableView它的contentHeight已经改变来更新它的滚动条?

How to notify QtQuick2 TableView that its contentHeight has changed to update its scroll bars?

我有一个 TableView,其中每个单元格由一个 Label 委托代表。此 Label 组件已将 wrapMode 设置为 Text.Wrap,这意味着它的高度可以在 TableView 调整大小时更改。

然而,TableView 似乎没有意识到它的 contentHeight 已经因为换行而改变,因此滚动条不会更新。如下所示:

如何通知 TableView 它的 contentHeight 已更改,以便在调整视图大小时滚动条相应地更新?

用于创建 table 的 QML 代码如上所示:

import QtQuick 2.12
import QtQuick.Controls 2.13
import QtQuick.Window 2.12
import Qt.labs.qmlmodels 1.0

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

    TableView {
        id: view
        anchors.fill: parent
        columnWidthProvider: () => width/2
        onWidthChanged: forceLayout()
        onHeightChanged: forceLayout()

        model: TableModel {
            TableModelColumn {display: "key"}
            TableModelColumn {display: "value"}
            rows: [
                {key: "first name", value: "Freida"},
                {key: "last name", value: "Vandervort"},
                {key: "date of birth", value: "03/05/1989"},
                {key: "street address", value: "977 Kuvalis Mountain"},
                {key: "city", value: "Lynchville"},
                {key: "country", value: "Dominican Republic"},
            ]
        }

        delegate: Label {
            padding: 10
            text: model.display
            wrapMode: Text.Wrap
            background: Rectangle {border.color: "black"}
        }

        ScrollBar.vertical: ScrollBar {policy: ScrollBar.AlwaysOn}
    }
}

解决方案是将代表的身高存储在一个数组中,并用它来计算 contentHeight。每当委托更改其大小时,都需要更新此数组。

TableView {
    //store delegate heights
    property var delegateHeights: Array(model.rowCount).fill(0)

    //use stored delegate heights to calculate content height
    contentHeight: delegateHeights.reduce((total, height) => total + height, 0)

    delegate: Label {
        //update stored delegate heights when delegate size changes
        onHeightChanged: view.delegateHeights = view.delegateHeights.map((el, index) => index === row ? height : el)

        ...
    }

    ...
}