为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

哆啦的时光机 2023-03-22 16:16:42
我正在寻找一种在 python 中用超过 10000 行数据填充 QTableModel 的快速方法。在双 for 循环中迭代项目需要 40 多秒。
查看完整描述

2 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

您不需要明确地将项目添加到 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_())


查看完整回答
反对 回复 2023-03-22
?
喵喔喔

TA贡献1735条经验 获得超5个赞

我建议创建一个 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


查看完整回答
反对 回复 2023-03-22
  • 2 回答
  • 0 关注
  • 320 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号