繁体   English   中英

TypeError:无法读取 QML 中 null 的属性“宽度”

[英]TypeError: Cannot read property 'width' of null in QML

Item {
    id: root
    width: 200
    height: head.height
    property bool state: false
    property alias root: root
    property alias head: head
    property alias body: body
    property alias title: title
    property alias image: image
    property alias mouseArea: mouseArea
    property var data // when i define data variable in this way, program gets error

    Tasks { id: tasks } // For call my c++ functions
    Rectangle {
        id: head
        width: parent.width
        height: 40
        color: "#333333"
        radius: 10

        ...
    }

    Rectangle {
        id: body
        visible: root.state
        color: "#0d0d0d"
        width: parent.width
        height: 0
        anchors.top: head.bottom
        anchors.topMargin: 1

        ...
    }

    function addItem(categoryName) {
        // let data = tasks.getJson() when i define data variable in this way, program works properly
        let date = Qt.formatDateTime(new Date(), "dd.MM.yyyy")
        for (let i = 0; i < Object.keys(data.categories).length; i++) {
            if (data.categories[i].name === categoryName) {
                for (let j = 0; j < Object.keys(data.categories[i].tasks).length; j++) {
                    if (date === data.categories[i].tasks[j].date)
                        listModel.append({_text: data.categories[i].tasks[j].name, _value: data.categories[i].tasks[j].score})
                    else {
                        //TODO: tasks.saveHistory(data)
                        data.categories[i].tasks[j].score = 0
                        data.categories[i].tasks[j].goal = 0
                        data.categories[i].tasks[j].date = date
                        listModel.append({_text: data.categories[i].tasks[j].name, _value: data.categories[i].tasks[j].score})
                        tasks.saveData(data)
                    }
                    body.height += 50
                }
            }
        }
    }
    Component.onCompleted: data = tasks.getJson()
}

我的问题是这样的:如果我在 addItem function 中定义数据变量,我的程序运行正常。 但是当我将数据变量定义为全局时,程序会出现以下错误:

qrc:/qml/PopUpGroupBox.qml:23: TypeError: Cannot read property 'width' of null
qrc:/qml/PopUpGroupBox.qml:72: TypeError: Cannot read property 'width' of null
Rectangle {
    id: head
    width: parent.width // line 23
    height: 40
    color: "#333333"
    radius: 10
    ...

Rectangle {
    id: body
    visible: root.state
    color: "#0d0d0d"
    width: parent.width // line 72
    height: 0
    anchors.top: head.bottom
    anchors.topMargin: 1
    ...

注意:我的 C ++ 代码也可以。 我已经测试过很多次了。

你的问题是因为 QML Item已经有一个data属性(链接),它有另一个目的。 因此,在这种情况下,您应该为变量使用不同的名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM