Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to show data dynamically in qml



  • This post is deleted!

  • Moderators

    It all depends on what you prefer and how complicated the data is. Here are some possibilities:

    • generate model using ListModel
    • push data to C++ and use a subclass of QAbstractItemModel
    • if the data is a simple list of strings, you can display it directly (just set it as model in ListView or something)

    A full list is in the docs: https://doc.qt.io/qt-5/qtquick-modelviewsdata-modelview.html#models


  • Qt Champions 2018

    If you fetch external data in JSON, I would use JsonListModel from https://github.com/benlau/qsyncable
    It acts as a proper QAbstractItemModel and make a diff of the changes between update to send the correct signals (dataChanged, rowsInserted,rowsRemoved, ...)

    Something like so:

    // asuming the JSON response is [{"id": 1, "foo":  "xxx", "bar": 42}.  {"id": 2, "foo":  "yyy", "bar": 43}]
    JsonListModel {
        id: jsonListModel
        keyField: "id"
    }
    
    ListView {
        anchors.fill: parent
        model: jsonListModel
        delegate: ItemDelegate { text: model.foo + " - " + model.bar  }
    }
    
    //...
    Timer {
         running: true
         interval: 5000
         triggeredOnStart: true
         repeat: true
         onTriggered: {
             var xhr = new XMLHttpRequest();
             xhr.onreadystatechange = function() {
                 if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200)
                     jsonListModel.source = JSON.parse(xhr.responseText);
             };
             xhr.open("GET", yourUrl);
             xhr.send();
         }
    }
    

    If you only fetch your data once and don't need to update it, you can just assign the result of JSON.parse to your ListView (or Repeater/MapItemView/Instantiator/...).


Log in to reply