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

art*_*pov 3 qt listview qt-quick

这是我的 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 { }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

文本和按钮全部被平滑的应用程序窗口

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

        delegate: PaymentMethods.Item {
            width: parent.width
            onPmSaved: {
                ListView.view.model.rename(index, newName)
            }
        }
Run Code Online (Sandbox Code Playgroud)

它看起来好多了:

应用程序窗口,文本和按钮很好地分开

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

qrc:/PaymentMethods.qml:32: TypeError: Cannot read property 'width' of null
Run Code Online (Sandbox Code Playgroud)

有没有一种好方法将 QML ListView 的委托宽度设置为完整父级的宽度?

poo*_*a13 6

ListView 文档中:

委托根据需要进行实例化,并且可以随时销毁。因此,状态永远不应该存储在委托中。委托通常是 ListView 的 contentItem 的父级,但通常取决于它在视图中是否可见,父级可以更改,有时为 null。因此,不建议从委托内绑定到父级的属性。如果您希望委托填充 ListView 的宽度,请考虑使用以下方法之一:

ListView {
    id: listView
    // ...

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

        // Correct.
        width: listView.width
        width: ListView.view.width
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)