spootnx spootnx - 6 months ago 161
Python Question

How to sort QTableView in Qt4 and up

enter image description here

Code creates a single

QTableView
. The column sorting was enabled.
When I click the column name (1,2 or 3 nothing happens).
How to make this sorting work without using proxy model?

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Model(QtCore.QAbstractTableModel):
def __init__(self):
QtCore.QAbstractTableModel.__init__(self)
self.items = [[1, 'one', 'ONE'], [2, 'two', 'TWO'], [3, 'three', 'THREE']]

def flags(self, index):
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable

def rowCount(self, parent=QtCore.QModelIndex()):
return 3
def columnCount(self, parent=QtCore.QModelIndex()):
return 3

def data(self, index, role):
if not index.isValid(): return

if role in [QtCore.Qt.DisplayRole, QtCore.Qt.EditRole]:
return self.items[index.row()][index.column()]

def onClick(index):
tableView.openPersistentEditor(tableView.model().index(index.row(), index.column()))
print 'clicked index: %s'%index

tableModel=Model()
tableView=QtGui.QTableView()
tableView.setModel(tableModel)
tableView.clicked.connect(onClick)
tableView.setSortingEnabled(True)

tableView.show()
app.exec_()

Answer

I am not a python developer, but it seems that there is no sort() method implemented in your model.

In C++, when you derive your custom model from the QAbstractItemModel (or QAbstractTableModel) you have to implement the QAbstractItemModel::sort() method in order to enable sorting.