我有一个变量,像下面的代码中的a
,其中有很多数据。我想在QListWidget或QListView中显示这些数据。我一直在使用QListWidget,但它比QListView消耗更多的内存,所以我选择了QListView。
但是在下面的代码中,显示QListView的速度比QListWidget慢。有没有什么方法可以解决这个问题?
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import time
app=QApplication([])
n=1000000
a=[]
for i in range(n):
a.append('asfghjkg'+str(i))
class TodoModel(QtCore.QAbstractListModel):
def __init__(self, todos=None):
super(TodoModel, self).__init__()
self.todos = todos or []
def data(self, index, role):
if role == Qt.DisplayRole:
# See below for the data structure.
return self.todos[index.row()]
# Return the todo text only.
def rowCount(self, index):
return len(self.todos)
todos = a
model = TodoModel(todos)
t=time.time()
win1=QListView()
win1.setUniformItemSizes(True)
win1.setViewMode(1)
win1.setWrapping(False)
win1.setFlow(QListWidget.TopToBottom)
win1.setModel(model)
win1.show()
print('show1',time.time()-t)
t=time.time()
win2=QListWidget()
win2.setUniformItemSizes(True)
win2.addItems(a)
win2.show()
print('show2',time.time()-t)
app.exec_()
我的电脑输出结果为:
(注意:原文即为中文,此处为翻译后的内容)show1 5.374950885772705
show2 1.3125648498535156
python -m cProfile -s cumtime yourcode.py
的命令运行你的代码,你就可以看到时间都花在哪里了。请注意,这并不仅仅是上面提到的对rowCount
和len
函数的数百万次调用。 - user9088793