How to show data in QML json request

南楼画角 提交于 2019-12-24 20:03:04

问题


So bear with me. How to create a model based on json? What is delegate? Is below logic is correct?

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

In below code I can not see any data on screen. How to show data in QML json request?

thanks

UPDATED WORKING CODE:

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()
    }
}

This tested on Qt5.9.2 using QML app project.


回答1:


Your example is totally wrong.

  1. JSON.parse() returns Object, not array. So you cannot call length() on it. Remember - {} - object, [] - array.

  2. Your request returns something like {"ip":"111.111.111.111"}. Where do you see Name here? So you should append items model.append( {"listdata": arr.ip }), not like you do it now. Don't forget to surround the parameter name with quotes.

  3. listview.model.append shoud be replaced with model.append. Learn what is Occam's razor.

  4. model is not good id for item. Using reserved words is a bad style.

So I advice you to read documentation twice when you facing such problems.



来源:https://stackoverflow.com/questions/47748402/how-to-show-data-in-qml-json-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!