Python Forum

Full Version: Sorting numerical values provided by QAbstractTableModel
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have subclassed QAbstractTableModel, and overwrote its data method like this:
    def data(self, index, role):
        if role == Qt.ItemDataRole.DisplayRole:
            value = self._daten.iloc[index.row(), index.column()]
            if isinstance(value, float): return "%.2f" % value
            if isinstance(value, str): return "%s" % value
            return str(value)
=> as you can see the method will always return a string. I figured out, if it's not a string, it will not be displayed in the QTableView.
But when I do now a sorting by using QSortFilterProxyModel numbers are now treaded like strings and the sorting is done on an alphanumerical basis.

self.model = mein_TableModel(daten)
self.proxymodel = QtCore.QSortFilterProxyModel() # <<-- I know, I should also use a subclassed QSortFilterProxyModel... but can't find a working example
self.proxymodel.setSourceModel(self.model)
self.FundamentalTabelle.setSortingEnabled(True)
self.FundamentalTabelle.setModel(self.proxymodel)
Sub-classing QSortFilterProxyModel and overriding it's lessThan method seems to be the right way. But all examples I found, resulted in new problems.
I even would not know, which of those examples I should post here to start with. Perhaps if somebody could direct me to a "golden-sample". Thanks!
(btw: my table has columns with text and columns with floats ... would be great if sorting could work on both types).