pyqt - populating QTableWidget with csv data

后端 未结 3 1612
悲&欢浪女
悲&欢浪女 2020-11-29 10:03

I have a QTableWidget, i export the data from this table to a csv file. But now, i want to Open a existing csv file and populate my table with this data. how can i do it?

相关标签:
3条回答
  • 2020-11-29 10:20

    Looks like you could use the csv module here:

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    import csv
    
    import sip
    sip.setapi('QString', 2)
    sip.setapi('QVariant', 2)
    
    from PyQt4 import QtGui, QtCore
    
    class MyWindow(QtGui.QWidget):
        def __init__(self, fileName, parent=None):
            super(MyWindow, self).__init__(parent)
            self.fileName = fileName
    
            self.model = QtGui.QStandardItemModel(self)
    
            self.tableView = QtGui.QTableView(self)
            self.tableView.setModel(self.model)
            self.tableView.horizontalHeader().setStretchLastSection(True)
    
            self.pushButtonLoad = QtGui.QPushButton(self)
            self.pushButtonLoad.setText("Load Csv File!")
            self.pushButtonLoad.clicked.connect(self.on_pushButtonLoad_clicked)
    
            self.pushButtonWrite = QtGui.QPushButton(self)
            self.pushButtonWrite.setText("Write Csv File!")
            self.pushButtonWrite.clicked.connect(self.on_pushButtonWrite_clicked)
    
            self.layoutVertical = QtGui.QVBoxLayout(self)
            self.layoutVertical.addWidget(self.tableView)
            self.layoutVertical.addWidget(self.pushButtonLoad)
            self.layoutVertical.addWidget(self.pushButtonWrite)
    
        def loadCsv(self, fileName):
            with open(fileName, "rb") as fileInput:
                for row in csv.reader(fileInput):    
                    items = [
                        QtGui.QStandardItem(field)
                        for field in row
                    ]
                    self.model.appendRow(items)
    
        def writeCsv(self, fileName):
            with open(fileName, "wb") as fileOutput:
                writer = csv.writer(fileOutput)
                for rowNumber in range(self.model.rowCount()):
                    fields = [
                        self.model.data(
                            self.model.index(rowNumber, columnNumber),
                            QtCore.Qt.DisplayRole
                        )
                        for columnNumber in range(self.model.columnCount())
                    ]
                    writer.writerow(fields)
    
        @QtCore.pyqtSlot()
        def on_pushButtonWrite_clicked(self):
            self.writeCsv(self.fileName)
    
        @QtCore.pyqtSlot()
        def on_pushButtonLoad_clicked(self):
            self.loadCsv(self.fileName)
    
    if __name__ == "__main__":
        import sys
    
        app = QtGui.QApplication(sys.argv)
        app.setApplicationName('MyWindow')
    
        main = MyWindow("/path/to/MyFile.csv")
        main.show()
    
        sys.exit(app.exec_())
    

    PyQt5 version:

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    import csv
    
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class MyWindow(QtWidgets.QWidget):
        def __init__(self, fileName, parent=None):
            super(MyWindow, self).__init__(parent)
            self.fileName = fileName
    
            self.model = QtGui.QStandardItemModel(self)
    
            self.tableView = QtWidgets.QTableView(self)
            self.tableView.setModel(self.model)
            self.tableView.horizontalHeader().setStretchLastSection(True)
    
            self.pushButtonLoad = QtWidgets.QPushButton(self)
            self.pushButtonLoad.setText("Load Csv File!")
            self.pushButtonLoad.clicked.connect(self.on_pushButtonLoad_clicked)
    
            self.pushButtonWrite = QtWidgets.QPushButton(self)
            self.pushButtonWrite.setText("Write Csv File!")
            self.pushButtonWrite.clicked.connect(self.on_pushButtonWrite_clicked)
    
            self.layoutVertical = QtWidgets.QVBoxLayout(self)
            self.layoutVertical.addWidget(self.tableView)
            self.layoutVertical.addWidget(self.pushButtonLoad)
            self.layoutVertical.addWidget(self.pushButtonWrite)
    
        def loadCsv(self, fileName):
            with open(fileName, "r") as fileInput:
                for row in csv.reader(fileInput):    
                    items = [
                        QtGui.QStandardItem(field)
                        for field in row
                    ]
                    self.model.appendRow(items)
    
        def writeCsv(self, fileName):
            with open(fileName, "w") as fileOutput:
                writer = csv.writer(fileOutput)
                for rowNumber in range(self.model.rowCount()):
                    fields = [
                        self.model.data(
                            self.model.index(rowNumber, columnNumber),
                            QtCore.Qt.DisplayRole
                        )
                        for columnNumber in range(self.model.columnCount())
                    ]
                    writer.writerow(fields)
    
        @QtCore.pyqtSlot()
        def on_pushButtonWrite_clicked(self):
            self.writeCsv(self.fileName)
    
        @QtCore.pyqtSlot()
        def on_pushButtonLoad_clicked(self):
            self.loadCsv(self.fileName)
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        app.setApplicationName('MyWindow')
    
        main = MyWindow("data.csv")
        main.show()
    
        sys.exit(app.exec_())
    
    0 讨论(0)
  • 2020-11-29 10:29
    import csv
     
    from PyQt5.QtCore import Qt
    from PyQt5.QtGui import QKeySequence, QCursor
    from PyQt5.QtWidgets import QAction, QApplication, QFileDialog, QMenu, QTableView
     
     
    class SEToolsTableView(QTableView):
     
        """QTableView class extended for SETools use."""
     
        def __init__(self, parent):
            super(SEToolsTableView, self).__init__(parent)
     
            # set up right-click context menu
            self.save_csv_action = QAction("Save table to CSV...", self)
            self.menu = QMenu(self)
            self.menu.addAction(self.save_csv_action)
     
            # connect signals
            self.save_csv_action.triggered.connect(self.choose_csv_save_location)
     
        def contextMenuEvent(self, event):
            self.menu.popup(QCursor.pos())
     
        def event(self, e):
            if e == QKeySequence.Copy or e == QKeySequence.Cut:
                datamodel = self.model()
     
                selected_text = []
                current_row = None
                current_col = None
                prev_row = None
                prev_col = None
                for index in sorted(self.selectionModel().selectedIndexes()):
                    current_row = index.row()
                    current_col = index.column()
     
                    if prev_row is not None and current_row != prev_row:
                        selected_text.append('\n')
                    elif prev_col is not None and current_col != prev_col:
                        selected_text.append('\t')
     
                    selected_text.append(datamodel.data(index, Qt.DisplayRole))
     
                    prev_row = current_row
                    prev_col = current_col
     
                QApplication.clipboard().setText("".join(selected_text))
                return True
     
            else:
                return super(SEToolsTableView, self).event(e)
     
        def choose_csv_save_location(self):
            filename = QFileDialog.getSaveFileName(self, "Save to CSV", "table.csv",
                                                   "Comma Separated Values Spreadsheet (*.csv);;"
                                                   "All Files (*)")[0]
     
            if filename:
                self.save_csv(filename)
     
        def save_csv(self, filename):
            """Save the current table data to the specified CSV file."""
     
            datamodel = self.model()
            row_count = datamodel.rowCount()
            col_count = datamodel.columnCount()
     
            with open(filename, 'w') as fd:
                writer = csv.writer(fd, quoting=csv.QUOTE_MINIMAL)
     
                # write headers
                csv_row = []
                for col in range(col_count):
                    csv_row.append(datamodel.headerData(col, Qt.Horizontal, Qt.DisplayRole))
     
                writer.writerow(csv_row)
     
                # write data
                for row in range(row_count):
                    csv_row = []
     
                    for col in range(col_count):
                        index = datamodel.index(row, col)
                        csv_row.append(datamodel.data(index, Qt.DisplayRole))
     
                    writer.writerow(csv_row)
    
    0 讨论(0)
  • 2020-11-29 10:32

    This is from a project of mine:

    def setup_relation(self,rel):
    
        self.table.insertRow(0)
    
        for i in rel.header.attributes:
            item=QtGui.QTableWidgetItem()
            item.setText(i)
            self.table.insertColumn(self.table.columnCount())
            self.table.setItem(0,self.table.columnCount()-1,item)
    
        for i in rel.content:
            self.table.insertRow(self.table.rowCount())
            for j in range(len(i)):
                item=QtGui.QTableWidgetItem()
                item.setText(i[j])
                self.table.setItem(self.table.rowCount()-1,j,item)
    
    0 讨论(0)
提交回复
热议问题