PDA

View Full Version : TypeError: Cannot read property 'length' of undefined in QML array



TheIndependentAquarius
11th June 2014, 12:02
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?

anda_skoa
11th June 2014, 12:39
Do you also get that when you run just Access.qml?
Have you tried without "newq"? You don't use that for access to "pp".

Cheers,
_

TheIndependentAquarius
11th June 2014, 14:01
Do you also get that when you run just Access.qml?
The error appears only when I access and thus assign the property of Access.qml in main.qml.


Have you tried without "newq"? You don't use that for access to "pp".
A drowning person grabs a straw. I tried newq because the original way wasn't working - I know it is not needed.

Would you please try the code on your machine (if you have it nearby)?

Thanks.

anda_skoa
11th June 2014, 15:36
The yy property is just not set yet when pp gets changed.

If you add a onYyChanged handler you'll see that it gets set after the other one.

So it is still undefined when the first change handler is invoked.

Cheers,
_

TheIndependentAquarius
12th June 2014, 07:26
thankful to you, got the point now.

wysota
12th June 2014, 07:34
In situations such as this it is wise to use a Component.onCompleted handler to make sure the other method only gets executed when the object is fully constructed:


Item {
property var prop
property var prop2

property bool __constructed: false

onPropChanged: {
if(!__constructed) return
doSomethingWith(prop2)
}
Component.onCompleted: {
__constructed = true
// do some other initial stuff
}
}

TheIndependentAquarius
12th June 2014, 07:39
wysota

That was very helpful - much thankful to you too.