QML: Cannot read property 'xxx' of undefined

泄露秘密 提交于 2019-12-23 20:22:12

问题


ApplicationWindow {
    id: root

    property string rootName: "--rootName"

    visible: true
    width: 800
    height: 400

    title: qsTr("WatchFace Maker")

    WatchLcd{
        property string watchLcdInApp: "watchLcdInApp"
        id: watchLcd
    }

    TextAdder{
        id: textAdder

        Component.onCompleted: {
            console.log("APP: ", root.watchLcd.watchLcdInApp)//#Error!!! remove root, it works.
        }
    }
}

I want to know:

  1. Why it doesn't work when I add root id in above commented line?

  2. How do children component access sibling component's property if children component is created from a XXX.qml file?


回答1:


The id property is a "special kind" of property, it is only resolved at "code time" and cannot be resolved during runtime.

root.watchLcd will not work because watchLcd is an id, and as such it can't be resolved with root.watchLcd

The id also logically works only in that particular source, and you only need that particular id regardless of the structure of the object tree, you don't need its parent id as in root.watchLcd

If you want to access a specific object from another file, naturally, this can't happen through its id. You can either use a property or a function for it:

//SomeItem.qml
Item {
  property alias text : obj.text
  Item  {
    id: obj
    property string text
  }
  property Item object : obj
  function getObj() { return obj }
}

/main.qml
Window {
  visible: true

  SomeItem {
    id: item
    text: "someText"
  }

  SomeItem {
    Component.onCompleted: {
      //console.log(item.obj.text) // TypeError: Cannot read property 'text' of undefined
      console.log(item.object.text) // someText
      console.log(item.getObj().text) // someText
    }
  }
}

Also, note how the property alias works - it may be useful in many cases, if all you need to access is a nested object's property you can expose it with an alias without needing access to the object externally.



来源:https://stackoverflow.com/questions/36736573/qml-cannot-read-property-xxx-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!