PDA

View Full Version : (PyQt) QSortFilterProxyModel very slow when sorting



TheGrudge
17th January 2021, 12:44
Hi, I have a table with two columns and approx. 50.000 rows of data. When I use the QSortFilterProxyModel, sorting is painfully slow.
I implemented a test model with one column and 500.000 string entries. When sorting with QSortFilterProxyModel, it takes approx. 5 seconds on my computer to sort. Using the builtin sort functions in Python it sorts instantly.
Is there any way to speed up the QSortFilterProxyModel? Or do I need to implement a custom sort method in all my models?

The test model looks like this, I hope it is correctly implemented, at least the correct index is returned when clicking on a row after sorting ;-)


import sys

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


class MyModel(QAbstractTableModel):

def __init__(self, parent=None):
super().__init__(parent)
self._data = [str(i).rjust(6, '0') for i in range(500_000)]

def data(self, index: QModelIndex, role=None):
if not index or not index.isValid():
return QVariant()
if index.column() == 0 and role == Qt.DisplayRole:
return self._data[index.row()]
return QVariant()

def rowCount(self, parent=None, *args, **kwargs):
return len(self._data)

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

def headerData(self, column, orientation, role=None):
if role == Qt.DisplayRole and orientation == Qt.Horizontal and column == 0:
return 'Values'
return QVariant()

def sort(self, column, order=None):
self.layoutAboutToBeChanged.emit()
if order == Qt.AscendingOrder:
self._data.sort()
else:
self._data.sort(reverse=True)
self.layoutChanged.emit()
self.dataChanged.emit(QModelIndex(), QModelIndex())


if __name__ == "__main__":
app = QApplication(sys.argv)

view = QTableView()
model = MyModel(view)
view.setModel(model)
view.resizeColumnsToContents()
view.horizontalHeader().setStretchLastSection(True )
view.setSortingEnabled(True)
view.sortByColumn(0, Qt.AscendingOrder)
view.show()

sys.exit(app.exec_())


But I wonder if it is possible to speed up the builtin Qt models, maybe there is a flag I'm not aware of?
Sorting 50.000 entries (or in this example 500.000 entries) should take that long?