根据 QML Treeview 中的项目深度更改行的高度

问题描述

我正在尝试根据树中的项目深度更改 TreeView 中行的高度。 itemDelegate 可以访问 depth 属性(因此我可以更改项目的高度),但只能从 rowDelegate 设置行高,无法看到项目深度。

正如您从示例中看到的,我需要更改行高以匹配深度。 rowdelegate 如何从模型中确定项目深度?

Component {
    id: delegateMenuItem
    Column {
        height: 100  // No effect
        spacing: 20  // No effect
        bottomPadding: 20 // No effect
        Rectangle {
            border {
                color: "blue"
                width: 2
            }
            color: "red"
            height: itemText.height * 2
            width: 300
            Text {
                id: itemText
                text: qsTr(styleData.value)+"-"+height
                color: "white"
                font.pointSize: fontSize(styleData.depth)
            }
        }
    }
}

enter image description here

解决方法

使用 QQC1 中的 TreeView,我建议您尝试为 implicitHeight 设置 itemDelegate,而不为 rowDelegate 设置任何高度。因此,请尝试将您的代码段更改为:

itemDelegate: Rectangle {
    id: delegateMenuItem

    border { color: "blue"; width: 2 }
    color: "red"
    width: ...
    implicitHeight: styleData.depth * ...
    
    Text {
        id: itemText
        
        anchors.fill: parent
        ...
    }
}

(在您当前的实现中,delegateMenuItem 没有任何 implicitHeight。这意味着它的 height 可能是 0。此外,您使用的 ColumnLayout 也是无用的,所以我已经删除了。)

我没有试过上面的。但是我已经尝试用 TreeView from Qt marketplace 做你想做的事。它旨在与 QQC2 配合使用,并基于 QQC2 的 TableView,因此您可以使用 rowHeightProvider