QTableWidget从json在Python中如何填充



我有这样的输出:

{'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"]

如何通过名称值进行搜索,使用QLabel字段来实现这一点?

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

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_())

如果您知道;标题";标签(密钥(,只需遍历它们即可获得相应的值:

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)

最新更新