如何在QML JSON请求中显示数据 [英] How to show data in QML json request

查看:896
本文介绍了如何在QML JSON请求中显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,请忍受我.如何创建基于json的模型?什么是代表? 下面的逻辑是正确的吗?

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

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

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

谢谢

更新后的工作代码:

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应用程序项目在Qt5.9.2上进行的测试.

This tested on Qt5.9.2 using QML app project.

推荐答案

您的示例完全错误.

  1. JSON.parse()返回Object,而不是数组.因此,您不能在其上调用length().记住-{}-对象,[]-数组.

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

您的请求返回类似{"ip":"111.111.111.111"}的内容.您在哪里看到Name?因此,您应该添加项目model.append( {"listdata": arr.ip }),而不是像现在这样.不要忘记用引号将参数名称引起来.

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.

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

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

model不是该项目的有效ID.使用保留字是一种不好的风格.

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.

这篇关于如何在QML JSON请求中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆