无法在 qml table 中正确显示 api 数据

Can't show api data in qml table correctly

我正在尝试从 api 获取数据并将其从 python 一侧插入到 table 视图中。 代码.

main.qml

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 1.4
import QtQuick.Controls 2.15

Window {
    width: 1200
    height: 500
    visible: true
    title: qsTr("TableView")

    Rectangle {
    anchors.fill: parent
    color: "#50505f"

    TableView {
        id: table

        anchors.fill: parent
        model: libraryModel

        rowDelegate: Rectangle {
            color: styleData.selected ? "5a53ff" : "#40405f"
            width: 2000
            height: 40
            border.width: 1
        }

        TableViewColumn {
            role: "title"
            title: "Title"
            width: 500
        }

        TableViewColumn {
            role: "author"
            title: "Author"
            width: 500
        }
    }
}

// Connections {
//     target: backend
// }
}

main.py

# This Python file uses the following encoding: utf-8
import os
import sys
from turtle import title
import requests
import json

from PySide2.QtCore import QObject, Slot, Signal
from PySide2.QtWidgets import QApplication
from PySide2.QtQml import QQmlApplicationEngine


if __name__ == "__main__":
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()

    # Get Context
    # main = MainWindow()
    url = "http://localhost:8085/api/supplier"
    response = requests.get(url).json()
    id = []
    name = []
    for obj in response:
        id.append(obj["supplier_id"])
        id.append(obj["supplier_name"])
    myModel = []

    engine.rootContext().setContextProperty("libraryModel", id) 

    engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

我明白错误是什么,基本上当它调用 api 时它设置它获得的第一个值并将它设置到两个字段,我希望数据被分开(id 应该去标题和作者姓名),但我似乎无法找到一种方法来做到这一点。任何帮助将非常感激。我已经研究了很长时间,但找不到解决方案。

您必须使用具有与“标题”和“作者”关联的自定义角色的模型:

import os
import sys
import requests
import json

from PySide2.QtCore import QObject, Qt, Slot, Signal
from PySide2.QtGui import QStandardItem, QStandardItemModel
from PySide2.QtWidgets import QApplication
from PySide2.QtQml import QQmlApplicationEngine

AUTHOR_ROLE = Qt.UserRole
TITLE_ROLE = Qt.UserRole + 1


class LibraryModel(QStandardItemModel):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setItemRoleNames({AUTHOR_ROLE: b"author", TITLE_ROLE: b"title"})

    def append(self, author, title):
        item = QStandardItem()
        item.setData(author, AUTHOR_ROLE)
        item.setData(title, TITLE_ROLE)
        self.appendRow(item)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()

    library_model = LibraryModel()

    # Get Context
    url = "http://localhost:8085/api/supplier"
    response = requests.get(url).json()

    for obj in response:
        author = obj["supplier_name"]
        title = obj["supplier_id"]
        library_model.append(author, title)

    engine.rootContext().setContextProperty("libraryModel", library_model)

    engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())