列表中元素的 QML 访问属性

QML access properties of elements in list

我有一个 MapPolyline 列表,我尝试将动态添加的对象保存到这个列表中。很好,但是当我尝试获取列表中的对象时,它不起作用。它说 TypeError: Cannot read property of undefined 这是我的代码

property list<MapPolyline> lines

 var component;
 var sprite;
 component = Qt.createComponent("lineStringComponent.qml");
 sprite = component.createObject(window,{"id": "button1"});
 sprite.addCoordinate(QtPositioning.coordinate(currentgcppoint.lat, currentgcppoint.lon));
 sprite.addCoordinate(gcppoint);
 map.addMapItem(sprite)
 lines.push(sprite)
 gcps.push(currentgcppoint)
 console.log("Added:", lines[1])
 console.log("width:", lines[1].line.width)

这里是lineStringComponent.qml

import QtQuick 2.2
import QtLocation 5.6
import QtPositioning 5.6
MapPolyline {
    id:polyline
    line.width: 3
    line.color: Qt.rgba(Math.random(),Math.random(),Math.random())
}

控制台输出为:

Added: undefined
TypeError: Cannot read property 'line' of undefined

它似乎在尝试创建新对象时有延迟。我们如何克服这种延迟?

如果我正确阅读了你的代码,你只会将 1 元素添加到 lines,然后你尝试使用 [ 检索 lines 的第二个元素=12=]。这明显是undefined.

尝试使用 line[0] 访问 lines 的第一个元素。
JS 数组的索引以 0 开头(与大多数语言一样)。

如果对象创建会有延迟,那么您将无法更改它的任何属性,而您可以这样做 (sprite.addCoordinate(...))