我正在开发统计软件,该软件将从Cloud Firestore数据库中获取数据,然后将其放入 QTableWidget 中,然后再放入图表中。我能够创建数据库的离线备份(下面的json)。我如何实现用来自其的数据填充 QTableWidget ?
在我的表格中,我有4个可见列-日期,类型,发布,已发送和一个隐藏-ID(格式化日期,例如050719)
这是我从数据库中获取的.json文件
"{\"events\": {\"050719\": {\"Type\": \"Conference\", \"Published\": \"4\", \"Sent\": \"3\", \"Date\": \"05.07.2019\"}, \"050919\": {\"Type\": \"Conference\", \"Published\": \"23\", \"Sent\": \"35\", \"Date\": \"05.09.2019\"}, \"120719\": {\"Type\": \"Conference\", \"Published\": \"3\", \"Sent\": \"4\", \"Date\": \"12.07.2019\"}, \"150719\": {\"Type\": \"Conference\", \"Published\": \"4\", \"Date\": \"15.07.2019\", \"Sent\": \"2\"}}}"
答案 0 :(得分:0)
没有通用方法,但是基本思想是遍历组件,如下所示:
import json
from PySide2 import QtWidgets
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
data = "{\"events\": {\"050719\": {\"Type\": \"Conference\", \"Published\": \"4\", \"Sent\": \"3\", \"Date\": \"05.07.2019\"}, \"050919\": {\"Type\": \"Conference\", \"Published\": \"23\", \"Sent\": \"35\", \"Date\": \"05.09.2019\"}, \"120719\": {\"Type\": \"Conference\", \"Published\": \"3\", \"Sent\": \"4\", \"Date\": \"12.07.2019\"}, \"150719\": {\"Type\": \"Conference\", \"Published\": \"4\", \"Date\": \"15.07.2019\", \"Sent\": \"2\"}}}"
# or
# with open('/path/of/json') as f:
# data = json.load(f)
d = json.loads(data)
keys = ["Date", "Type", "Published", "Sent"]
labels = keys + ["ID"]
w = QtWidgets.QTableWidget(0, len(labels))
w.setColumnHidden(4, True)
w.setHorizontalHeaderLabels(labels)
for i, (key, value) in enumerate(d["events"].items()):
rows = [value[k] for k in keys] + [key]
w.insertRow(w.rowCount())
for j, v in enumerate(rows):
it = QtWidgets.QTableWidgetItem(v)
w.setItem(i, j, it)
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
更新:
import json
from PySide2 import QtCore, QtWidgets
class DateTimeDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(DateTimeDelegate, self).initStyleOption(option, index)
value = index.data()
option.text = QtCore.QDateTime.fromMSecsSinceEpoch(value).toString("dd.MM.yyyy")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
data = # ...
d = json.loads(data)
keys = ["Date", "Type", "Published", "Sent"]
labels = keys + ["ID"]
w = QtWidgets.QTableWidget(0, len(labels))
delegate = DateTimeDelegate(w)
w.setItemDelegateForColumn(0, delegate)
w.setColumnHidden(4, True)
w.setHorizontalHeaderLabels(labels)
for i, (key, value) in enumerate(d["events"].items()):
rows = [
value[k]
if k != "Date"
else QtCore.QDateTime.fromString(value[k], "dd.MM.yyyy").toMSecsSinceEpoch()
for k in keys
] + [key]
w.insertRow(w.rowCount())
for j, v in enumerate(rows):
it = QtWidgets.QTableWidgetItem()
it.setData(QtCore.Qt.DisplayRole, v)
w.setItem(i, j, it)
w.resize(640, 480)
w.show()
sys.exit(app.exec_())