如何在不出现“ TypeError:无法读取null的属性'width'”错误的情况下使用ListView?

问题描述

我正在使用Qt 5.15.1开发应用程序。在QML方面,我正在使用ListView,这在控制台中给我以下错误:

TypeError:无法读取null的属性“ width”

寻找原因,我注意到,即使是QtCreator中新的QtQuick Scroll应用程序的最基本的样板代码:

import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    width: 640
    height: 480
    visible: true
    title: qsTr("Scroll")

    ScrollView {
        anchors.fill: parent

        ListView {
            width: parent.width
            model: 20
            delegate: ItemDelegate {
                text: "Item " + (index + 1)
                width: parent.width // <-- The line in the error message
            }
        }
    }
}
当用鼠标拖动视图时,

会产生此错误。当我将整个ScrollView项目替换为来自ItemDelegate文档的代码段时,也会发生这种情况:

ListView {
    width: 160
    height: 240

    model: Qt.fontFamilies()

    delegate: ItemDelegate {
        text: modelData
        width: parent.width // <-- The line in the error message
        onClicked: console.log("clicked:",modelData)
    }

    ScrollIndicator.vertical: ScrollIndicator { }
}

当我注释掉width: parent.width绑定时,在两种情况下错误都消失了。显然,这会影响每行的宽度。

TypeError: Cannot read property 'width' of null in QML中接受的答案对我来说没有帮助。

如何使这项工作按预期进行?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)