我有一个保存大量数据的QTableView,并且我正在尝试实现复制/粘贴功能,但是.selectedIndexes()
和.data()
的性能却很慢。我想加快此过程...复制粘贴到Excel中的1000x1000单元是瞬时的,但是在我的代码中,仅5秒钟即可获取表的索引,然后15秒钟即可读取所有索引。
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import Qt
import pandas as pd
import numpy as np
import sys
import time
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, df):
super().__init__()
self.df = df
def columnCount(self, parent=None):
return self.df.columns.size
def rowCount(self, parent=None):
return self.df.index.size
def data(self, index, role=None):
row = index.row()
col = index.column()
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.ToolTipRole:
return str(self.df.iat[row,col])
class TableView(QtWidgets.QTableView):
def __init__(self, series):
super().__init__()
self.setModel(TableModel(df))
self.horizontalHeader().hide()
self.verticalHeader().hide()
def copy(self):
# Set up clipboard object
app = QtWidgets.QApplication.instance()
if not app:
app = QtWidgets.QApplication(sys.argv)
clipboard = app.clipboard()
a = time.time()
indexes = self.selectedIndexes()
b = time.time()
print('selectedIndexes runtime:',b-a)
data_time = 0
text = ""
prev_row = None
for ix in indexes:
if prev_row is None:
prev_row = ix.row()
a = time.time()
value = str(self.model().data(self.model().index(ix.row(), ix.column()), role=Qt.DisplayRole))
b = time.time()
data_time += b-a
if text == "":
# First item
text = value
elif ix.row() != prev_row:
# New row
text += '\n' + value
prev_row = ix.row()
else:
text += '\t' + value
print('.data runtime:', data_time)
clipboard.setText(text)
def keyPressEvent(self, event):
QtWidgets.QTableView.keyPressEvent(self, event)
if event.matches(QtGui.QKeySequence.Copy):
print('Ctrl + C')
self.copy()
# Examples
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
df = pd.DataFrame(np.random.randn(1000, 1000))
view = TableView(df)
view.show()
sys.exit(app.exec_())
输出
selectedIndexes runtime: 4.855096101760864
.data runtime: 17.418293476104736