0

我有一个 XmlListModel,它最初查询一个本地 XML 文件,该文件有一个世界共同城市的列表以及它们的纬度和经度。如果用户在该本地列表中找不到城市,XML ListModel 然后查询在线 API 以检索城市的纬度、经度。

因此,如代码所示,默认情况下,它使用 localCityUrl() 函数作为其源来显示本地城市列表。

XmlListModel {
        id: searchCityModel;

        source: localCityUrl()
        query: "/geonames/geoname"

        XmlRole { name: "city"; query: "toponymName/string()"; isKey: true }
        XmlRole { name: "country"; query: "countryName/string()"; isKey: true }
        XmlRole { name: "lat"; query: "lat/string()"; isKey: true }
        XmlRole { name: "lng"; query: "lng/string()"; isKey: true }

        onSourceChanged: reload();
    }

ListView {
        id: worldList

        anchors { left: parent.left; right: parent.right }
        height: units.gu(50)
        model: searchCityModel
        currentIndex: -1            

        delegate: Column {
            text: searchCityModel.status == XmlListModel.Ready ? searchCityModel.get(index).city + ", " + searchCityModel.get(index).country : console.log("Loading..")
            selected: worldList.currentIndex == index;
        }
    }

在这一点上一切都很好。然而,当用户在线搜索一个城市时(因为它在本地列表中不可用),它会更改源以查询在线 API,该 API 默认始终返回 5 个结果(与用户搜索词的最佳匹配)。

我包含了一个后退按钮,单击该按钮会使用下面的代码将 XML ListModel 源更改回本地文件,

searchCityModel.source = localCityUrl();

但是,在这样做时,我收到错误消息,

TypeError: Cannot read property 'city' of undefined

它基本上是在抱怨它试图读取 Xml ListModel 的值以分配给文本委托的行。

我如何确保它只在 Xml ListModel 准备好时才尝试这样做?我已经尝试在 Xml ListModel 中使用 onStatusChanged。

奇怪的是,它仅在从在线更改为本地时才抱怨源更改。所以当用户第一次在线搜索时,并没有显示任何错误。但是只有当用户按下后退按钮切换到本地源时,才会出现错误。

4

1 回答 1

2

您实际上没有正确使用 ListModel 中的模型,这可能会导致您的问题。您的委托应使用底层模型向委托公开的属性。通过调用 searchCityModel.get(index) 您没有使用绑定到 ListView 的模型。你的代表应该看起来更像下面

ListView {
        id: worldList

        anchors { left: parent.left; right: parent.right }
        height: units.gu(50)
        model: searchCityModel    

        delegate: Rectangle {
            width: worldList.width
            height: 20 //This has to be hardcoded to avoid the binding loop with the MouseArea

            text: city + ", " + country
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    worldList.currentIndex = index;
                }
            }
        }
    }
于 2013-06-20T21:37:45.157 回答