【发布时间】:2019-12-18 00:25:57
【问题描述】:
我在下面的代码中有一个像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
显示2 1.3125648498535156
【问题讨论】:
-
这不是一个很好的分析方法。使用
python -m cProfile -s cumtime yourcode.py之类的代码运行您的代码,您将看到时间都花在了哪里。请注意,它不仅存在于上述对rowCount和len的数百万次调用中。
标签: python performance pyqt5 qlistwidget qlistview