szotsaki
szotsaki

Reputation: 694

QML ListView height with multiple nested models

I have a ListView with a simple model which in turn also has a model which is actually displayed:

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
            }
        }
    }
}

I can get the Text and the Column height. Even though ListModel knows the Column height, it still has zero height.

My question is: how to properly assign ListView the given size?

The program outputs:

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

Upvotes: 0

Views: 1597

Answers (1)

szotsaki
szotsaki

Reputation: 694

Based on @folibis' suggestion, I changed the contentHeight and contentWidth properties when the delegate's height or width changes. After adding anchors to ListView, it perfectly works together with the encompassing item.

Here is the code:

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
            }
        }
    }
}

Inspired by @BaCaRoZzo's comment, if one would not need a ListView, the problem can solved without it:

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
                    }
                }
            }
        }
    }
}

Upvotes: 1

Related Questions