如何在tabWidget的两个QTableViews中显示两个不同的CSV文件?

时间:2019-02-17 15:22:01

标签: python pyqt5

我能够加载CSV文件并将其写入QTableView,但是,我希望能够修改此代码,以便能够在两个单独的tableViews中为两个不同的CSV文件执行此操作,并带有两个选项卡一个QTabWidget。

@Injectable()
export class RetryInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const { shouldRetry } = this;
    return next.handle(request)
      .pipe(retryWhen(genericRetryStrategy({
        shouldRetry
      })));
  }

  private shouldRetry = (error) => error.status === 502;
}

我知道如何将两个表视图添加到单独的选项卡小部件中,这只是用于处理两个单独的csv文件的加载和写入按钮的方法。

1 个答案:

答案 0 :(得分:1)

在您的情况下,每个选项卡中应有2个相同类型的小部件,因此创建自定义类是一个不错的选择。另一方面,最好通过对话获取CSV,因为如果要加载另一个文件,则必须修改代码,而用户则不应这样做。最后,我将创建一个QMainWindow,将在其中放置QTabWidget,并在每个选项卡中设置自定义窗口小部件。

import sys
import csv
from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.setGeometry(0, 0, 800, 420)

        self.model = QtGui.QStandardItemModel(self)
        self.tableView = QtWidgets.QTableView()
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setStretchLastSection(True)

        self.pushButtonLoad = QtWidgets.QPushButton("Load Csv File!",
            clicked=self.on_pushButtonLoad_clicked)

        self.pushButtonWrite = QtWidgets.QPushButton("Write Csv File!",
            clicked=self.on_pushButtonWrite_clicked)

        layoutVertical = QtWidgets.QVBoxLayout(self)
        layoutVertical.addWidget(self.tableView)
        layoutVertical.addWidget(self.pushButtonLoad)
        layoutVertical.addWidget(self.pushButtonWrite)

    def loadCsv(self, fileName):
        self.model.clear()
        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, lineterminator='\n')  
            print('rowCount->', self.model.rowCount())
            for rowNumber in range(self.model.rowCount()):
                fields = [
                    self.model.item(rowNumber, columnNumber).text()
                    for columnNumber in range(self.model.columnCount())
                ]
                print('fields->', fields)
                writer.writerow(fields)

    @QtCore.pyqtSlot()
    def on_pushButtonWrite_clicked(self):
        fileName, _ =  QtWidgets.QFileDialog.getSaveFileName(self, self.tr("Open CSV"), 
            QtCore.QDir.currentPath(), self.tr("CSV Files (*.csv)"))
        if fileName:
            self.writeCsv(fileName)

    @QtCore.pyqtSlot()
    def on_pushButtonLoad_clicked(self):
        fileName, _ =  QtWidgets.QFileDialog.getOpenFileName(self, self.tr("Open CSV"), 
            QtCore.QDir.currentPath(), self.tr("CSV Files (*.csv)"))
        if fileName:
            self.loadCsv(fileName)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        tabwidget = QtWidgets.QTabWidget()
        self.setCentralWidget(tabwidget)
        tabwidget.addTab(Widget(), "tab1")
        tabwidget.addTab(Widget(), "tab2")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName('MyWindow')
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())