在Qt Quick 中,如何确保ListView 的委托宽度等于视图的宽度?

In Qt Quick, how to ensure a ListView's delegate's width to equal the view's width?

这是我的 QML 视图:

// Imports ommitted

Item {
    id: paymentMethods
    required property PaymentMethodsModel model

    ColumnLayout {
        anchors.fill: parent;

        Text {
            text: "Payment methods";
        }

        ListView {
            Layout.fillHeight: true
            Layout.fillWidth: true
            model: paymentMethods.model
            delegate: PaymentMethods.Item { }
        }

        ToolBar { }
    }
}

问题是,它看起来像这样:

我认为这是因为委托没有指定宽度,因为如果我这样做:

        delegate: PaymentMethods.Item {
            width: parent.width
            onPmSaved: {
                ListView.view.model.rename(index, newName)
            }
        }

看起来好多了:

问题是,当我进行重新排序项目的编辑时,出现此错误:

qrc:/PaymentMethods.qml:32: TypeError: Cannot read property 'width' of null

有什么好的方法可以将 QML ListView 的委托宽度设置为父级的完整宽度?

在重新排序的过渡中,item没有parent,所以错误提示,一个可能的解决方案是根据有无parent来设置item的宽度。

width: parent ? parent.width : 40 // default value

来自ListView documentation:

Delegates are instantiated as needed and may be destroyed at any time. As such, state should never be stored in a delegate. Delegates are usually parented to ListView's contentItem, but typically depending on whether it's visible in the view or not, the parent can change, and sometimes be null. Because of that, binding to the parent's properties from within the delegate is not recommended. If you want the delegate to fill out the width of the ListView, consider using one of the following approaches instead:

ListView {
    id: listView
    // ...

    delegate: Item {
        // Incorrect.
        width: parent.width

        // Correct.
        width: listView.width
        width: ListView.view.width
        // ...
    }
}