我有一个具有多个表视图的应用程序,其中引用了许多QStandardItemModel,我需要从文件中保存和加载这些信息。我尝试直接酸洗模型,但不可能。我该如何序列化模型并以读/写模式访问它们?
以下是我用于将模型存储为excel文件的代码:
@pyqtSlot()
def export(self):
filename, _ = QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)")
wbk = xlwt.Workbook()
sheet = wbk.add_sheet("sheet", cell_overwrite_ok=True)
style = xlwt.XFStyle()
font = xlwt.Font()
font.bold = True
style.font = font
for c in range(self.QSModel.columnCount()):
text = self.QSModel.headerData(c, Qt.Horizontal)
sheet.write(0, c + 1, text, style=style)
for r in range(self.QSModel.rowCount()):
text = self.QSModel.headerData(r, Qt.Vertical)
sheet.write(r + 1, 0, text, style=style)
for c in range(self.QSModel.columnCount()):
for r in range(self.QSModel.rowCount()):
text = self.QSModel.data(self.QSModel.index(r, c))
sheet.write(r + 1, c + 1, text)
wbk.save(filename)
这是我用来序列化文件中模型的代码:
@pyqtSlot()
def export2(self):
file_ = QtCore.QFile("file.dat")
file_.open(QtCore.QIODevice.WriteOnly)
# we will serialize the data into the file
out = QtCore.QDataStream(file_)
# serialize a string
out.writeQVariant(self.QSModel)
如何有效地管理持久文件上的读/写操作?