admin管理员组

文章数量:1415664

Alias.qml

import QtQuick 2.0

Rectangle {
    width: 100
    height: 62

    property var arr : [1,2,3,4]
}

Access.qml

import QtQuick 2.0

Rectangle {
    id: newq

    width: 100
    height: 62

    property var yy : [1]
    property var pp : [1]

    onPpChanged:
    {
        console.log("\npp: " +  pp.pop())
        console.log("\nyy: " + newq.yy.length + "\n")
    }
}

main.qml

import QtQuick 2.0

Rectangle {
    id: root
    width: 360
    height: 360

    Alias
    {
        id: poi
    }

    Access
    {
        pp: poi.arr
    }
}

The error shows up on this line:
console.log("\nyy: " + newq.yy.length + "\n")

Where am I going wrong?

Alias.qml

import QtQuick 2.0

Rectangle {
    width: 100
    height: 62

    property var arr : [1,2,3,4]
}

Access.qml

import QtQuick 2.0

Rectangle {
    id: newq

    width: 100
    height: 62

    property var yy : [1]
    property var pp : [1]

    onPpChanged:
    {
        console.log("\npp: " +  pp.pop())
        console.log("\nyy: " + newq.yy.length + "\n")
    }
}

main.qml

import QtQuick 2.0

Rectangle {
    id: root
    width: 360
    height: 360

    Alias
    {
        id: poi
    }

    Access
    {
        pp: poi.arr
    }
}

The error shows up on this line:
console.log("\nyy: " + newq.yy.length + "\n")

Where am I going wrong?

Share Improve this question asked Jun 11, 2014 at 10:01 Aquarius_GirlAquarius_Girl 23k71 gold badges249 silver badges441 bronze badges 2
  • Check if this might be helpful: qt-project/forums/viewthread/15244 and qt-project/doc/qt-5/qml-var.html – trainoasis Commented Jun 11, 2014 at 10:07
  • Perhaps you should use "variant" instead of var there? (see second code block here: qt-project/doc/qt-4.8/qml-variant.html) – trainoasis Commented Jun 11, 2014 at 10:14
Add a ment  | 

1 Answer 1

Reset to default 4

This happens because the yy property has not yet been initialised when pp is changed. You can see this by changing Access.qml:

import QtQuick 2.0

Rectangle {
    id: newq

    width: 100
    height: 62

    property var yy : [1]
    property var pp : [1]

    onYyChanged: console.log("yy changed: " + yy)

    onPpChanged:
    {
        console.log("pp changed: " + pp)
        console.log("\nyy: " + newq.yy.length + "\n")
    }
}

This outputs:

qml: pp changed: 1,2,3,4

file:///E:/Dev/Projects/qt/qml-test/Access.qml:17: TypeError: Cannot read property 'length' of undefined

qml: yy changed: 1

You can see that yy is eventually initialised, but not before pp. You should guard against this with an if (newq.yy) check, or refactor the code to avoid this situation, if possible.

The order of property assignments and bindings should not be relied upon, as QML is a declarative language.

Some related reading:

  • QML Applications
  • JavaScript Expressions in QML Documents
  • Property Binding

本文标签: javascriptTypeError Cannot read property 39length39 of undefined in QML arrayStack Overflow