猿问

如何在 pyqt 中用数据快速填充 QTableView/Model

我正在寻找一种在 python 中用超过 10000 行数据填充 QTableModel 的快速方法。

在双 for 循环中迭代项目需要 40 多秒。


哆啦的时光机
浏览 321回答 2
2回答

守着星空守着你

您不需要明确地将项目添加到 QTableModel,您可以围绕现有数据结构构建自己的模型,例如列表列表或如下所示的 numpy 数组。from PyQt5 import QtWidgets, QtCore, QtGuiimport sysfrom PyQt5.QtCore import QModelIndex, Qtimport numpy as npclass MyTableModel(QtCore.QAbstractTableModel):    def __init__(self, data=[[]], parent=None):        super().__init__(parent)        self.data = data    def headerData(self, section: int, orientation: Qt.Orientation, role: int):        if role == QtCore.Qt.DisplayRole:            if orientation == Qt.Horizontal:                return "Column " + str(section)            else:                return "Row " + str(section)    def columnCount(self, parent=None):        return len(self.data[0])    def rowCount(self, parent=None):        return len(self.data)    def data(self, index: QModelIndex, role: int):        if role == QtCore.Qt.DisplayRole:            row = index.row()            col = index.column()            return str(self.data[row][col])if __name__ == '__main__':    app = QtWidgets.QApplication(sys.argv)    # data = [[11, 12, 13, 14, 15],    #         [21, 22, 23, 24, 25],    #         [31, 32, 33, 34, 35]]    data = np.random.random((10000, 100)) * 100    model = MyTableModel(data)    view = QtWidgets.QTableView()    view.setModel(model)    view.show()    sys.exit(app.exec_())

喵喔喔

我建议创建一个 QStandardItem 的 numpy 数组并使用 appendColumn 函数填充模型:start = time.time()data = np.empty(rows, cols, dtype=object)              # generate empty data-Array#### Fill the data array with strings here ###items = np.vectorize(QStandardItem)(data)              # generate QStandardItem-Arrayprint(time.time() - start, "seconds to create items")start = time.time()# iterate over columns (because we have segneficantly less columns than rows)for i in range(len(cols)):     self.myQTableModel.appendColumn(items[:,i])self.myQTableModel.setHorizontalHeaderLabels(headerarray)    # set headersprint(time.time()-start, "seconds to load DB")16000 行和 7 列的结果:0.346372127532959 seconds to create items1.1745991706848145 seconds to load DB
随时随地看视频慕课网APP

相关分类

Python
我要回答