TypeError:无法读取QML中null的属性'width'

问题描述 投票:0回答:1
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函数中定义了数据变量,则我的程序可以正常工作。但是,当我将数据变量定义为全局变量时,程序会收到以下错误:

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
    ...

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

qt qml
1个回答
2
投票

您的问题是因为QML Item已经获得data属性(link),这还有另一个用途。因此,在这种情况下,您应该为变量使用其他名称。

© www.soinside.com 2019 - 2024. All rights reserved.