亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 229 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號