python-3.x 加载新数据后刷新QTableView

slwdgvem  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(243)

我试图在加载新的csv后更新一个表/表模型,这样它就可以显示新的值。更新小部件也可以处理这个问题吗?我已经在下面减少了很多代码。你可以使用任何2列csv:
0,0,
0,0,
0,0,

import pandas as pd

from PySide2 import QtWidgets, QtGui, QtCore

def read_data(fname):
    df = pd.read_csv(fname, sep=',', usecols=(0, 1), header=None)
    df = df.dropna(how='any')
    df = df[pd.to_numeric(df[0], errors='coerce').notnull()]
    data_arr = df.to_numpy(dtype='float64')

    return data_arr

class CustomTableModel(QtCore.QAbstractTableModel):
    def __init__(self, data=None):
        QtCore.QAbstractTableModel.__init__(self)
        self.load_data(data)

    def load_data(self, data):
        self.input_x = data[:, 0]
        self.input_y = data[:, 1]
        self.column_count = 2
        self.row_count = len(self.input_x)

    def rowCount(self, parent=QtCore.QModelIndex()):
        return self.row_count

    def columnCount(self, parent=QtCore.QModelIndex()):
        return self.column_count

    def headerData(self, section, orientation, role):
        if role != QtCore.Qt.DisplayRole:
            return None
        if orientation == QtCore.Qt.Horizontal:
            return ("x", "y")[section]
        else:
            return "{}".format(section)

    def data(self, index, role=QtCore.Qt.DisplayRole):
        column = index.column()
        row = index.row()

        if role == QtCore.Qt.DisplayRole:
            if column == 0:
                return str(self.input_x[row])
            elif column == 1:
                return str(self.input_y[row])
        elif role == QtCore.Qt.BackgroundRole:
            return QtGui.QColor(QtCore.Qt.white)
        elif role == QtCore.Qt.TextAlignmentRole:
            return QtCore.Qt.AlignRight

        return None

class Widget(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        try:
            self.data
        except AttributeError:
            self.open_csv()

        self.model = CustomTableModel(self.data)
        self.table_view = QtWidgets.QTableView()
        self.table_view.setModel(self.model)

        resize = QtWidgets.QHeaderView.ResizeToContents
        self.horizontal_header = self.table_view.horizontalHeader()
        self.vertical_header = self.table_view.verticalHeader()
        self.horizontal_header.setSectionResizeMode(resize)
        self.vertical_header.setSectionResizeMode(resize)
        self.horizontal_header.setStretchLastSection(False)

        # Creating layout
        self.main_layout = QtWidgets.QVBoxLayout()

        self.file_button = QtWidgets.QPushButton('CSV Import', self)
        self.file_button.clicked.connect(self.open_csv)

        self.main_layout.addWidget(self.table_view)
        self.main_layout.addWidget(self.file_button)

        self.setLayout(self.main_layout)

    def open_csv(self):
        filename, *_ = QtWidgets.QFileDialog.getOpenFileName(self, self.tr('Open CSV'),
                                                             self.tr("~/Desktop/"), self.tr('Files (*.csv)'))
        self.data = read_data(filename)
        return None

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, widget):
        QtWidgets.QMainWindow.__init__(self)
        self.setWindowTitle('Linear Plotter')
        self.setCentralWidget(widget)

        self.menu = self.menuBar()
        self.file_menu = self.menu.addMenu('File')

        exit_action = QtWidgets.QAction('Exit', self)
        exit_action.setShortcut(QtGui.QKeySequence.Quit)
        exit_action.triggered.connect(self.close)
        self.file_menu.addAction(exit_action)

        self.status = self.statusBar()
        self.status.showMessage('Data loaded and plotted')

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    widget = Widget()
    window = MainWindow(widget)
    window.show()

    sys.exit(app.exec_())

不确定QWidget.update()是否可以工作?我无法让它工作。

lymnna71

lymnna711#

一旦通过.setModel将模型分配给QTableView,则通过模型信号.layoutChanged通知视图模型已经改变
所以尝试self.model.layoutChanged.emit()

相关问题