pyqt - populating QTableWidget with csv data

2019-01-15 11:49发布

问题:

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?? This is my export code, i want a "populate" code, and i really dont know how to do it.. i know how to read a csv but i dont know how to populate my table with this csv data.

def export(self):

    nomeArquivo = "nomeArquivo"
    filename = unicode(QFileDialog.getSaveFileName(self, "Document - Choose Export File", nomeArquivo+".csv"))
    if not filename:
            return
    self.model.sort()
    fh = None
    try:

            fh = QFile(filename)
            if not fh.open(QIODevice.WriteOnly):                     
                raise IOError, unicode(fh.errorString())
            stream = QTextStream(fh)
            stream.setCodec("UTF-8")              
            for row in range(self.model.rowCount()):
                TSentence = self.model.data(
                self.model.index(row, TABELA.SENTENCE)).toString()
                TIrony = self.model.data(   
                self.model.index(row, TABELA.IRONY)).toString()

                stream  << "\""<< TSentence << "\"" << ";" << "\""<< TIrony <<"\"" <<"\n" 

    except (IOError, OSError), e:
        QMessageBox.warning(self, "Text - Error",
                "Failed to export: %s" % e)

    finally:
        if fh:
            fh.close()
    QMessageBox.warning(self, "Text - Export",
            "Successfully exported text to %s" % filename)

回答1:

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


回答2:

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)