Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. JSON data not appearing in QTableModel
Qt 6.11 is out! See what's new in the release blog

JSON data not appearing in QTableModel

Scheduled Pinned Locked Moved Solved Qt for Python
6 Posts 2 Posters 1.9k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F Offline
    F Offline
    Fakhr
    wrote on last edited by
    #1

    Hi, I created a table using QML, I wanted to add JSON data inside the table. The problem is that I can only see the last row of JSON data for e.g. if I added a new entry then I can only see that entry not the pervious ones. Any help would be really appreciated. Code is given below:

    main.qml

    import QtQuick 2.15
    import QtQuick.Window 2.15
    import QtQuick.Controls 2.15
    import QtQuick.Controls 1.4 as OldControls
    import QtQml.Models 2.15
    import TbModel 1.0
    
    
    OldControls.ApplicationWindow {
    id: window
    visible: true
    width: 1900
    height: 600
    
    OldControls.TableView
    {
        id: idtable
        width: parent.width
        height: parent.height
        model: TbModel{ }
        OldControls.TableViewColumn {
            role: "customer_id"
            title: "customer_id"
        }
        OldControls.TableViewColumn {
            role: "customer_code"
            title: "customer_code"
        }
        OldControls.TableViewColumn {
            role: "customer_name"
            title: "customer_name"
        }
    
        OldControls.TableViewColumn {
            role: "contact"
            title: "contact"
        }
    
        OldControls.TableViewColumn {
            role: "address"
            title: "address"
        }
    }
    }
    

    Table.py

    from PySide2.QtCore import QAbstractListModel, QModelIndex, QObject, Qt, Slot
    import requests
    import json
    
    class TbModel(QAbstractListModel):
        def __init__(self, parent: QObject = None) -> None:
            super().__init__(parent)
            self.headers = ["customer_id", "customer_code", "customer_name", "contact", "address"] 
            r = requests.get("http://192.168.10.5:8085/api/customer") # api I created 
            x = r.json()
            for i in x:
                self.rows = [
                   (i["customer_id"], i["customer_code"], i["customer_name"], i["contact"], 
       i["address"]),
                   (i["customer_id"], i["customer_code"], i["customer_name"], i["contact"], 
       i["address"])
    
        ]
    
    def rowCount(self, parent=QModelIndex()):
        return len(self.rows)
    
    def data(self, index, role=Qt.DisplayRole):
        row = index.row()
        if 0 <= row < self.rowCount():
            if role in self.roleNames():
                name_role = self.roleNames()[role].decode()
                col = self.headers.index(name_role)
                return self.rows[row][col]
    
    def headerData(self, section, orientation, role):
        if role == Qt.DisplayRole and 0 <= section < len(self.headers):
            return self.headers[section]
    
    def roleNames(self):
        roles = {}
        for i, header in enumerate(self.headers):
            roles[Qt.UserRole + i + 1] = header.encode()
        return roles
    
    @Slot(result="QVariantList")
    def roleNameArray(self):
        return self.headers
    

    main.py

    import os
    import sys
    from PySide2 import QtCore, QtGui, QtSql, QtQml
    from Table import TbModel
    from PySide2.QtWidgets import QApplication
    from PySide2.QtQml import QQmlApplicationEngine
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        engine = QQmlApplicationEngine()
        QtQml.qmlRegisterType(TbModel, "TbModel", 1, 0, "TbModel")
    
        engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))
    
        if not engine.rootObjects():
            sys.exit(-1)
        sys.exit(app.exec_())
    

    I'm working on a project and so I need to add the data from the api into the table, but I can only see the latest results from the api not the previous ones.

    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      @Fakhr said in JSON data not appearing in QTableModel:

      for i in x:
      self.rows = [
      (i["customer_id"], i["customer_code"], i["customer_name"], i["contact"],
      i["address"]),
      (i["customer_id"], i["customer_code"], i["customer_name"], i["contact"],
      i["address"])

      ]
      

      You are overwriting the content of self.rows each iteration of your loop.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      F 1 Reply Last reply
      1
      • SGaistS SGaist

        Hi,

        @Fakhr said in JSON data not appearing in QTableModel:

        for i in x:
        self.rows = [
        (i["customer_id"], i["customer_code"], i["customer_name"], i["contact"],
        i["address"]),
        (i["customer_id"], i["customer_code"], i["customer_name"], i["contact"],
        i["address"])

        ]
        

        You are overwriting the content of self.rows each iteration of your loop.

        F Offline
        F Offline
        Fakhr
        wrote on last edited by
        #3

        @SGaist Could u suggest a solution for this.

        1 Reply Last reply
        0
        • SGaistS Offline
          SGaistS Offline
          SGaist
          Lifetime Qt Champion
          wrote on last edited by
          #4

          Append rather than replace.

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          F 1 Reply Last reply
          1
          • SGaistS SGaist

            Append rather than replace.

            F Offline
            F Offline
            Fakhr
            wrote on last edited by
            #5

            @SGaist Could you maybe explain with some code. Not the entire process, just a single line, so that I can get a general idea of what I need to do.

            1 Reply Last reply
            0
            • SGaistS Offline
              SGaistS Offline
              SGaist
              Lifetime Qt Champion
              wrote on last edited by
              #6
              self.rows.append(your_data)
              

              You should read the Python list type documentation.

              In the absolute, you could use a list comprehension to build your rows.

              Beware that you are putting the same data twice.

              Interested in AI ? www.idiap.ch
              Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

              1 Reply Last reply
              2

              • Login

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • Users
              • Groups
              • Search
              • Get Qt Extensions
              • Unsolved