How to show data in QML json request

2019-09-16 15:33发布

问题:

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.