如何在PyQt4中加载和保存数据?

时间:2017-11-29 03:10:35

标签: python python-2.7 pyqt pyqt4

我试图编写一个应用来处理数据保存和使用QTableWidget加载。

我想编写一个更复杂的应用程序,因此,我使用许多pyqt类来定义不同的页面。 这是代码:

import sys
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QMainWindow.__init__(self)

        load_file = QtGui.QAction("Load", self)
        load_file.triggered.connect(self.loadFile)
        save_file = QtGui.QAction("Save", self)
        save_file.triggered.connect(self.saveFile)

        menubar = self.menuBar()
        file = menubar.addMenu('&File')
        file.addAction(load_file)
        file.addAction(save_file)

        table = Table()

        self.setCentralWidget(table)

    def loadFile(self):
        load_file = QtGui.QFileDialog.getOpenFileName(self, "Open file", "./", "All files(*)")
        if load_file:
            with open(load_file, "r") as load_data:
                data = eval(load_data.read())

            Table().filling(data)

    def saveFile(self):
        save_file = QtGui.QFileDialog.getSaveFileName(self, "Save file", "./", "All files(*)")
        if save_file:
            with open(save_file, "w") as save_data:
                save_data.write(repr(DATA))

class Table(QtGui.QTableWidget):
    def __init__(self, parent = None):
        QtGui.QTableWidget.__init__(self)

        self.setRowCount(4)
        self.setColumnCount(2)
        self.itemChanged.connect(self.getData)

    def getData(self):
        data = []
        for row in range(4):
            row_data = []
            for col in range(2):
                if self.item(row, col):
                    text = self.item(row, col).text()
                    row_data.append(str(text))
                else:
                    row_data.append("")
            data.append(row_data)
        global DATA
        DATA = data

    def filling(self, data):
        for row in range(4):
            for col in range(2):
                new_item = QtGui.QTableWidgetItem("")
                self.setItem(row, col, new_item)
                self.item(row, col).setText(data[row][col])

app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())

该应用程序可以在QTableWidget中保存数据过滤,但无法显示已加载的数据。 enter image description here 我想知道问题所在。

0 个答案:

没有答案