Qt快速控件ListView大小问题

Qt quick controls ListView size issue

我在使用 Qt Quick Controls 2 时遇到弹出 window 大小行为的问题。当我将 ListView 作为 Popup window 的 contentItem 时,弹出 window 大小为零。一些重现问题的示例代码:

import QtQuick 2.4
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ApplicationWindow {
    id: window
    visible: true
    width: 800
    height: 600

    Button {
        text: "open popup"
        onClicked: popup.open()
    }

    Popup {
        id: popup
        x: (window.width - width) / 2
        y: window.height / 6
        width: contentWidth
        height: contentHeight

        contentItem: ListView {
            width: contentWidth
            height: contentHeight
            model: ListModel {
                ListElement {
                    name: "Apple"
                    cost: 2.45
                }
                ListElement {
                    name: "Orange"
                    cost: 3.25
                }
                ListElement {
                    name: "Banana"
                    cost: 1.95
                }
            }

            delegate: RowLayout {
                Label {
                    text: name
                }
                Label {
                    text: cost
                }
            }
        }
    }
}

如何让popup适应ListView的大小?

垂直 ListView 不提供内容宽度。它总是 -1。您必须指定一些内容,例如:

Popup {
    id: popup
    x: (window.width - width) / 2
    y: window.height / 6

    contentItem: ListView {
        implicitWidth: 200 // <==
        implicitHeight: contentHeight
        //...
    }
}