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

How to quickly fill a QTableView/Model with data in pyqt

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

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

我建议创建 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-Array
print(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 headers
print(time.time()-start, "seconds to load DB")

16000 行和 7 列的结果:

0.346372127532959 seconds to create items
1.1745991706848145 seconds to load DB

您不需要显式地将项目添加到 QTableModel,您可以围绕现有数据结构构建自己的模型,例如列表列表或如下所示的 numpy 数组。

from PyQt5 import QtWidgets, QtCore, QtGui
import sys
from PyQt5.QtCore import QModelIndex, Qt
import numpy as np

class 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_())