【发布时间】:2021-12-11 13:00:16
【问题描述】:
我使用 qml 创建了一个表,我想在表中添加 JSON 数据。问题是我只能看到最后一行 json 数据,例如如果我添加了一个新条目,那么我只能看到那个条目而不是之前的条目。
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"
}
}
}
表格.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_())
我不知道为什么它只显示最近的结果,我可以理解它是否向我显示了第一个结果(这很可能表明我需要使用循环)。任何帮助将不胜感激。
【问题讨论】: