Search code examples
pythonpyqt5argumentsqtablewidget

How to pass QTableWidget as an argument on function


I have exporting to excel function and bunch of QTableWidgets. I know it is very inefficient if I make every function for each tablewidget but how can I pass tablewidget as an argument of a function?

    def writeCsv(self):
        path, _ = QFileDialog.getSaveFileName(self, 'Save File', QDir.homePath() + "/export.csv", "CSV Files(*.csv *.txt)")
        if path:
            with open(path, 'w') as stream:
                print("saving", path)
                writer = csv.writer(stream, dialect = 'excel', delimiter = ',')
                headers = []
                for column in range(self.tableWidget_show.columnCount()):
                    header = self.tableWidget_show.horizontalHeaderItem(column)
                    if header is not None:
                        headers.append(header.text())
                    else:
                        headers.append("Column " + str(column))
                writer.writerow(headers)
                for row in range(self.tableWidget_show.rowCount()):
                    rowdata = []
                    for column in range(self.tableWidget_show.columnCount()):
                        item = self.tableWidget_show.item(row, column)
                        if item is not None:
                            rowdata.append(item.text())
                        else:
                            rowdata.append('')
                    writer.writerow(rowdata)

I want to use self.tableWidget_show part as an argument so I can just change the argument everytime when I have other Qtablewidget


Solution

  • First of all make each function execute the smallest task so that debugging is easy, for example in your case it is not necessary to use a QFIleDialog there to select a file, but only receive the path, and in another function make that selection . On the other hand, the information used is stored in the model and not in the view, so it could be generalized by saving a model instead of a QTableWidget, so you could also use it for any type of QTableView.

    def write_model_to_csv(self, model, filename):
        with open(filename, "w") as stream:
            writer = csv.writer(stream, dialect="excel", delimiter=",")
            headers = []
            for column in range(model.columnCount()):
                text = model.headerData(column, Qt.Horizontal)
                if text:
                    headers.append(text)
                else:
                    headers.append("Column {}".format(column))
            writer.writerow(headers)
            for row in range(model.rowCount()):
                rowdata = []
                for column in range(model.columnCount()):
                    text = model.index(row, column).data()
                    if text:
                        rowdata.append(text)
                    else:
                        rowdata.append("")
                writer.writerow(rowdata)
    
    path, _ = QFileDialog.getSaveFileName(
        self, "Save File", QDir.homePath() + "/export.csv", "CSV Files(*.csv *.txt)"
    )
    if path:
        self.write_model_to_csv(self.tableWidget_show.model(), path)