CPU 从 QAbstractListModel 更新 QListView 时过载

CPU overload when updating QListView from QAbstractListModel

我正在构建一个小的 pyqt5 应用程序,它在 QListView 中显示 512 个值的列表。该列表通过单独的线程更新,使用 QThread。 它工作得很好,除了它使用了我正在开发的(旧)Core 2 Duo 2,53 Ghz 的 CPU 的 65/95%。

我简化了代码以删除依赖项,因为更新是通过网络协议完成的。每秒更新 40 次(每次 25 毫秒)。

下面的简化脚本每秒刷新列表 10 次,更新列表时 CPU 仍为 65%。

有什么办法可以避免过载吗? 是否有一些最佳实践可用于更新视图?

(global没有在我上次的代码中,这里有一个简单的例子)

from random import randrange
from time import sleep
from sys import argv, exit
from PyQt5.QtCore import QThread, QAbstractListModel, Qt, QVariant, pyqtSignal
from PyQt5.QtWidgets import QListView, QApplication, QGroupBox, QVBoxLayout, QPushButton

universe_1 = [0 for i in range(512)]

class SpecialProcess(QThread):
    universeChanged = pyqtSignal()
    def __init__(self):
        super(SpecialProcess, self).__init__()
        self.start()

    def run(self):
        global universe_1
        universe_1 = ([randrange(0, 101, 2) for i in range(512)])
        self.universeChanged.emit()
        sleep(0.1)
        self.run()


class Universe(QAbstractListModel):
    def __init__(self, parent=None):
        super(Universe, self).__init__(parent)

    def rowCount(self, index):
        return len(universe_1)

    def data(self, index, role=Qt.DisplayRole):
        index = index.row()
        if role == Qt.DisplayRole:
            try:
                return universe_1[index]
            except IndexError:
                return QVariant()
        return QVariant()


class Viewer(QGroupBox):
    def __init__(self):
        super(Viewer, self).__init__()
        list_view = QListView()
        self.list_view = list_view
        # create a vertical layout
        vbox = QVBoxLayout()
        universe = Universe()
        vbox.addWidget(list_view)
        # Model and View setup
        self.model = Universe(self)
        self.list_view.setModel(self.model)
        # meke a process running in parallel 
        my_process = SpecialProcess()
        my_process.universeChanged.connect(self.model.layoutChanged.emit)
        # set the layout on the groupbox
        vbox.addStretch(1)
        self.setLayout(vbox)


if __name__ == "__main__":
  app = QApplication(argv)
  group_widget = Viewer()
  group_widget.show()
  exit(app.exec_())

这似乎是一个正常的行为......