import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def __init__(self, parent=None):
super().__init__(parent)
self._data = [str(i).rjust(6, '0') for i in range(500_000)]
if not index or not index.isValid():
if index.column() == 0 and role == Qt.DisplayRole:
return self._data[index.row()]
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'
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()
if __name__ == "__main__":
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_())
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_())
To copy to clipboard, switch view to plain text mode
Bookmarks