QTableView horizo​​ntalHeader 让它变得很慢?

QTableView horizontalHeader makes it very laggy?

我有下面的代码,我注意到当我按 ctrl+A 到 select 所有行时感觉很慢,大约需要 1 秒才能完成 selection。但是,我还注意到,如果我用 self.horizontalHeader().hide() 隐藏水平 header,延迟就会完全消失!为什么会这样?我怎样才能摆脱滞后但保持我的 header?

from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import Qt
import pandas as pd
import numpy as np
import sys

class SeriesModel(QtCore.QAbstractTableModel):
    def __init__(self, series):
        super().__init__()
        self.series = series

    def columnCount(self, parent=None):
        return 1

    def rowCount(self, parent=None):
        return len(self.series)

    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.series[row])

    # The headers of this table will show the level names of the MultiIndex
    def headerData(self, section, orientation, role=None):
        if role in [QtCore.Qt.DisplayRole, QtCore.Qt.ToolTipRole]:
            if orientation == Qt.Horizontal:
                return str(self.series.name)

class SeriesView(QtWidgets.QTableView):
    def __init__(self, series):
        super().__init__()

        self.setModel(SeriesModel(series))

        # self.horizontalHeader().hide()

# Examples
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    series = pd.Series(np.random.randn(1000000)).rename('MyData')

    view = SeriesView(series)
    view.show()

    sys.exit(app.exec_())

问题是 highlightSections 属性 在 QTableView header 中默认启用。这 属性 意味着如果选择了一个项目,则也选择了 header 中暗示重绘的项目,在您的情况下,您有 1000000,因此它将被重绘类似的次数。所以一个可能的解决方案是禁用 属性:

class SeriesView(QtWidgets.QTableView):
    def __init__(self, series):
        super().__init__()
        self.setModel(SeriesModel(series))
        self.horizontalHeader().setHighlightSections(False)