如何在QML json请求中显示数据

时间:2017-12-11 07:45:59

标签: json listview model qml httprequest

所以请耐心等待。如何基于json创建模型?什么是代表? 以下逻辑是否正确?

Model -> delegate -> json request -> json get -> show to list view

在下面的代码中,我无法在屏幕上看到任何数据。如何在QML json请求中显示数据?

感谢

更新的工作代码:

import VPlayApps 1.0
import QtQuick 2.0
import QtQuick 2.3
import QtQuick.Controls 1.2
import "qrc:/"

Item {
    id: item1
     anchors.fill: parent


    ListModel {
        id: ***modelListIP***
    }

    ListView {
        id: listview
        anchors.fill: parent
        model: ***modelListIP***
        delegate: Text {
            text: listdata
        }
    }

    function getData() {
        var xmlhttp = new XMLHttpRequest();
        var url = "https://api.ipify.org?format=json";

        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200) {
                myFunction(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

    function myFunction(response) {
        var objValue = JSON.parse(response);
            ***modelListIP.append( {"listdata": objValue.ip })***
    }

    Button {
        anchors.bottom: parent.bottom
        width: parent.width
        text: "Get Data"
        onClicked: getData()
    }
}

使用QML app项目在Qt5.9.2上进行了测试。

1 个答案:

答案 0 :(得分:1)

你的例子是完全错误的。

  1. JSON.parse()返回Object,而非数组。所以你不能在上面调用length()。请记住 - {} - 对象,[] - 数组。

  2. 您的请求会返回{"ip":"111.111.111.111"}之类的内容。你在哪里看到Name?因此,您应该追加项目model.append( {"listdata": arr.ip }),而不是像现在这样做。不要忘记用引号括住参数名称。

  3. listview.model.append应替换为model.append。了解什么是Occam's razor

  4. model不是商品的好ID。使用保留字是一种不好的风格。

  5. 因此,当您遇到此类问题时,我建议您阅读两次文档。