如何将 QTableWidget 作为参数传递给函数

How to pass QTableWidget as an argument on function

我有导出到 excel 功能和一堆 QTableWidgets。我知道如果我为每个 tablewidget 创建每个函数是非常低效的,但是我如何将 tablewidget 作为函数的参数传递?

    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)

我想使用 self.tableWidget_show 部分作为参数,这样每次当我有其他 Qtablewidget

时我都可以更改参数

首先让每个函数执行最小的任务,这样调试就容易了,例如在你的情况下,没有必要在那里使用 QFIleDialog select 一个文件,而只接收路径,在另一个函数中使 selection 。另一方面,所使用的信息存储在模型中而不是视图中,因此可以通过保存模型而不是 QTableWidget 来概括它,因此您也可以将它用于任何类型的 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)