QTableWidget from json in Python 如何填充

QTableWidget from json in Python how to fill

我有这样的输出:

{'heatpump': [{'Topic': 'TOP0', 'Name': 'Heatpump_State', 'Value': '1', 'Description': 'On'}, {'Topic': 'TOP1', 'Name': 'Pump_Flow', 'Value': '9.08', 'Description': 'l/min'},{.........}, {.......}]}

如果我们制作这样的键,如何填充QTableWidget

keys = ["Topic", "Name", "Value", "Description"]

以及如何通过 Name 值进行搜索,使用 QLabel 字段来实现这个?

添加部分代码,如何在此处枚举行并将所有值添加到 table 而不是最后一个值?:

from PySide2 import QtWidgets


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)


    data = {'heatpump': [{'Topic': 'TOP0', 'Name': 'Heatpump_State', 'Value': '1', 'Description': 'On'}, {'Topic': 'TOP1', 'Name': 'Pump_Flow', 'Value': '9.08', 'Description': 'l/min'}]}
    d = data
    keys = ["Topic", "Name", "Value", "Description"]
    labels = keys + ["ID"]
    #i = 0
    w = QtWidgets.QTableWidget(5, len(labels))
    w.setColumnHidden(4, True)
    w.setHorizontalHeaderLabels(labels)
    for record in d["heatpump"]:
        print(record)
        for i, (name, value) in enumerate(record.items()):
            print(i, name, value)
            it = QtWidgets.QTableWidgetItem(value)
            w.setItem(0, i, it)


    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

如果您知道“header”标签(键),只需遍历它们即可获得相应的值:

    keys = "Topic", "Name", "Value", "Description"
    for row, record in enumerate(d["heatpump"]):
        print(record)
        for column, key in enumerate(keys):
            it = QtWidgets.QTableWidgetItem(record.get(key, ""))
            w.setItem(row, column, it)