<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView]]></title><description><![CDATA[<p dir="auto">Hello,</p>
<p dir="auto">I Have a QTableView, this is my (basic) architecture of my models setup</p>
<pre><code>class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):

	def __init__(self, parent=None):

		ProxyModel = ProxyModel() 
		TableModel = TableModel()
		ProxyModel.setSourceModel(TableModel)

		self.MyTableView.setModel(ProxyModel)
</code></pre>
<p dir="auto">I've achieved the filtering with success by reimplementing <code>FilterAcceptsrow()</code> in ProxyModel class (QSortFilterProxyModel Subsclass). I want to reimplement <code>lessThan()</code> method in ProxyModel to achieve sorting. However, even though been documenting on it, I still can't figure out how to do it.</p>
<p dir="auto">Can someone explain to me the basis of how to reimplement this method so I can sort my QTableView on the 4th column for example.<br />
Thanks.</p>
<p dir="auto">Here's the ProxModel and TableModel implementation:</p>
<pre><code>class ProxyModel(QtCore.QSortFilterProxyModel):
	def __init__(self,parent=None):
		super(ProxyModel, self).__init__()
		self._filter = "Aucun"

	def setFilterColumn(self, header):
		if header == "Aucun": 
			self.Filtre("Aucun")
			return True
		for col in range(self.sourceModel().columnCount()):
			if self.sourceModel().headerData(col) == header:
				self.setFilterKeyColumn(col)
				return True
		return False

	def Filtre(self, valeur):
		self._filter = str(valeur)
		self.invalidateFilter()
	
	def filterAcceptsRow(self, sourceRow, sourceParent):
		if self._filter == "Aucun": return True

		sourceModel = self.sourceModel()
		id = sourceModel.index(sourceRow, self.filterKeyColumn(), sourceParent)
		if sourceModel.data(id) == self._filter:
			return True
		return False

class TableModel(QtCore.QAbstractTableModel):

	def __init__(self, mlist=None):
		super(TableModel, self).__init__()
		self._items = [] if mlist == None else mlist
		self._header = []
	def rowCount(self, parent = QtCore.QModelIndex):
		return len(self._items)

	def columnCount(self, parent = QtCore.QModelIndex):
		return len(self._header)

	def data(self, index, role = QtCore.Qt.DisplayRole):
		if not index.isValid():
		   return None
		if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
			return self._items[index.row()][index.column()]
		return None
	
	def setData(self, index, value, role = QtCore.Qt.EditRole):
		if value is not None and role == QtCore.Qt.EditRole:
			self._items[index.row()-1][index.column()] = value
			self.dataChanged.emit(index, index)
			return True
		return False

	def addRow(self, rowObject, row=False):
		if not row:
			row = self.rowCount()
		self.beginInsertRows(QtCore.QModelIndex(), row, row)
		self._items.append(rowObject)
		self.endInsertRows()
		self.layoutChanged.emit()

</code></pre>
]]></description><link>https://forum.qt.io/topic/122038/how-to-reimplement-lessthan-method-in-qsortfilterproxymodel-subclass-for-sorting-qtableview</link><generator>RSS for Node</generator><lastBuildDate>Sat, 14 Mar 2026 13:24:38 GMT</lastBuildDate><atom:link href="https://forum.qt.io/topic/122038.rss" rel="self" type="application/rss+xml"/><pubDate>Wed, 23 Dec 2020 10:58:59 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView on Wed, 23 Dec 2020 15:02:39 GMT]]></title><description><![CDATA[<p dir="auto">Thanks <a class="plugin-mentions-user plugin-mentions-a" href="/user/jonb">@<bdi>JonB</bdi></a> for your thoughtful answer. It gave me more insight on the logic of lessThan().<br />
I'll give this a big try and see where I'll get.</p>
<p dir="auto">Wish you a good day !</p>
]]></description><link>https://forum.qt.io/post/634039</link><guid isPermaLink="true">https://forum.qt.io/post/634039</guid><dc:creator><![CDATA[hachbani]]></dc:creator><pubDate>Wed, 23 Dec 2020 15:02:39 GMT</pubDate></item><item><title><![CDATA[Reply to How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView on Wed, 23 Dec 2020 14:17:50 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/hachbani">@<bdi>hachbani</bdi></a><br />
You cannot sort by "secondary", <em>multiple</em> columns by calling <code>sort()</code> multiple times.  The latest call simply replaces any earlier calls.</p>
<p dir="auto">Here indeed is where you <em>will</em> need to implement <code>lessThan()</code> correctly and in a more complex scenario.</p>
<p dir="auto">Take your apparent example of column #2 is the "primary" sort column and column #3 is the "secondary" sort column, meaning it only comes into play when two rows have the same value in column #2.  Now you will need code like:</p>
<pre><code>def lessThan(source_left: QModelIndex, source_right: QModelIndex) -&gt; bool:
    if source_left.column() == 2:
        if source_left.data() &lt; source_right.data()
            return True;
        elif source_left.data() &gt; source_right.data()
            return False;
        else
            return lessThan(source_left.siblingAtColumn(3), source_right.siblingAtColumn(3))
    return QSortFIlterProxyModel.lessThan(source_left, source_right)
</code></pre>
<p dir="auto">To implement "I want to only apply the sorting on the rows 1 --&gt; 20" you would have to do something like look at the <code>row()</code> numbers in the passed in indexes and act accordingly.  This would be <em>source</em> (not proxy) model row numbers.  And you'll have to return <em>something</em> when asked to compare rows &gt; 20.  Plus, don't forget, your rows in the source are also <em>filtered</em> to only include certain ones, so the row numbers will not be what you might expect.   You may not be able to <em>preserve</em> the order you would not have seen without sorting.  You cannot <em>instruct</em> the sort not to happen on certain rows.  It's a bit hokey, a sort is a sort, but you can implement whatever you like.</p>
]]></description><link>https://forum.qt.io/post/634034</link><guid isPermaLink="true">https://forum.qt.io/post/634034</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Wed, 23 Dec 2020 14:17:50 GMT</pubDate></item><item><title><![CDATA[Reply to How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView on Wed, 23 Dec 2020 13:49:33 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jonb">@<bdi>JonB</bdi></a></p>
<p dir="auto">Do you know if there's a way to call only sort method on only a slice of the table: instead of sorting all the table, I want to only apply the sorting on the rows 1 --&gt; 20 for example. Is that possible ?</p>
]]></description><link>https://forum.qt.io/post/634029</link><guid isPermaLink="true">https://forum.qt.io/post/634029</guid><dc:creator><![CDATA[hachbani]]></dc:creator><pubDate>Wed, 23 Dec 2020 13:49:33 GMT</pubDate></item><item><title><![CDATA[Reply to How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView on Wed, 23 Dec 2020 13:39:05 GMT]]></title><description><![CDATA[<p dir="auto">Hey ! I've done that, It was calling the <code>QSortFilterProxyModel::sort(int column, Qt::SortOrder order = Qt::AscendingOrder)</code> That I was missing to get an understanding of how this works ! I've tried to sort on a single column and It worked. Thanks !!</p>
<p dir="auto">I've read somewhere that in order to get multiple columns sorting, you need to call the sorting method on every column.</p>
<pre><code>self.MyTableView.model().sort(2, QtCore.Qt.AscendingOrder)
self.MyTableView.model().sort(3, QtCore.Qt.AscendingOrder)
</code></pre>
<p dir="auto">I've tried that, and, as expected, the sorting on the second column is no more on.</p>
<p dir="auto">I'll look through how to achieve multiple column sorting.</p>
<p dir="auto">Thanks again  <a class="plugin-mentions-user plugin-mentions-a" href="/user/jonb">@<bdi>JonB</bdi></a> !</p>
]]></description><link>https://forum.qt.io/post/634028</link><guid isPermaLink="true">https://forum.qt.io/post/634028</guid><dc:creator><![CDATA[hachbani]]></dc:creator><pubDate>Wed, 23 Dec 2020 13:39:05 GMT</pubDate></item><item><title><![CDATA[Reply to How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView on Wed, 23 Dec 2020 13:14:57 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/hachbani">@<bdi>hachbani</bdi></a><br />
OK, then you don't want to enable column click sorting (for now).  So just call <code>QSortFilterProxyModel::sort(int column, Qt::SortOrder order = Qt::AscendingOrder)</code> on the 4th column.  And implement <code>lessThan()</code> the way I showed above, for your "specific order" that you want on the 4th column.</p>
<p dir="auto">I don't know what else there is to say, just do it.</p>
]]></description><link>https://forum.qt.io/post/634026</link><guid isPermaLink="true">https://forum.qt.io/post/634026</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Wed, 23 Dec 2020 13:14:57 GMT</pubDate></item><item><title><![CDATA[Reply to How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView on Wed, 23 Dec 2020 13:03:35 GMT]]></title><description><![CDATA[<p dir="auto">After adding all the data I want to display to my QtableView, I want to display them in a specific order, hence the urge to wanting to implement a lessThan() method, so I can do it programmatically.</p>
<p dir="auto">To my understanding, If I set up the sorting in my TableView (setSortingEnabled(true)), This will give the option to sort the columns by clicking on the header, which is still something that I'd like to have in my app, but it doesn't solve my problem of displaying the data in the order I want.</p>
<p dir="auto">I might be wrong, as I'm just trying to learn about sorting in Qt, what do you think about my understanding of this ?</p>
]]></description><link>https://forum.qt.io/post/634024</link><guid isPermaLink="true">https://forum.qt.io/post/634024</guid><dc:creator><![CDATA[hachbani]]></dc:creator><pubDate>Wed, 23 Dec 2020 13:03:35 GMT</pubDate></item><item><title><![CDATA[Reply to How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView on Wed, 23 Dec 2020 12:58:00 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/hachbani">@<bdi>hachbani</bdi></a><br />
Since the data you show looks perfectly sortable --- a boolean, a string, an integer columns --- I would not epect you to need to override <code>lessThan</code> at all here.  Why do you think you need to?  You just ought set up sorting by columns on the <code>QTableView</code> (<code>QTableView::setSortingEnabled(true)</code>) and off you go?</p>
<p dir="auto">As for the parameters to <code>lessThan(source_left, source_right)</code>, if you do choose to implement it.  Don't worry about the names, left/right.  This function will be called by Qt repeatedly.  Each time these parameters are just <code>QModelIndex</code>es into your data.  The <em>rows</em> will differ, but the <em>columns</em> will always be the same, your sort column index.  Your only job is to return a <code>bool</code> according as you want the data at the first index to be treated as "less than", for the purpose of sorting, the data at the second one.</p>
]]></description><link>https://forum.qt.io/post/634022</link><guid isPermaLink="true">https://forum.qt.io/post/634022</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Wed, 23 Dec 2020 12:58:00 GMT</pubDate></item><item><title><![CDATA[Reply to How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView on Wed, 23 Dec 2020 12:45:36 GMT]]></title><description><![CDATA[<p dir="auto">Thanks for your answer. Well, What I really want to achieve is sorting on 3 columns, my column 1 hold boolean values, col 2 holds string values and third one holds Integer values. You can see the example in the image attached to get more understanding.</p>
<p dir="auto"><img src="https://ddgobkiprc33d.cloudfront.net/8b213f44-4beb-4fb0-af33-230c62f159e6.PNG" alt="Capture.PNG" class=" img-fluid img-markdown" /></p>
<p dir="auto">The aim of my post is to get an understanding about the lessThan() function, (the left and right inputs, what does those mean ? I get that those are indexes, but of what ?)</p>
<p dir="auto">If I understand how the sorting according to 1 column works, maybe I can implement the sorting I want.</p>
]]></description><link>https://forum.qt.io/post/634021</link><guid isPermaLink="true">https://forum.qt.io/post/634021</guid><dc:creator><![CDATA[hachbani]]></dc:creator><pubDate>Wed, 23 Dec 2020 12:45:36 GMT</pubDate></item><item><title><![CDATA[Reply to How to reimplement LessThan() method in QSortFIlterProxyModel subclass for Sorting QTableView on Wed, 23 Dec 2020 12:59:53 GMT]]></title><description><![CDATA[<pre><code>def lessThan(source_left: QModelIndex, source_right: QModelIndex) -&gt; bool:
    return source_left.data() &lt; source_right.data()
</code></pre>
<p dir="auto">But that's the default implementation anyway if you don't override it.  See <a href="https://doc-snapshots.qt.io/qtforpython-dev/PySide2/QtCore/QSortFilterProxyModel.html#PySide2.QtCore.PySide2.QtCore.QSortFilterProxyModel.lessThan" target="_blank" rel="noopener noreferrer nofollow ugc">https://doc-snapshots.qt.io/qtforpython-dev/PySide2/QtCore/QSortFilterProxyModel.html#PySide2.QtCore.PySide2.QtCore.QSortFilterProxyModel.lessThan</a> for what it can handle.  You only need to override if you have a more complex data object or criteria for sorting.  Since you say nothing about what your "4th column" is I cannot say further.</p>
<p dir="auto">You might write something along the lines of:</p>
<pre><code>def lessThan(source_left: QModelIndex, source_right: QModelIndex) -&gt; bool:
    if source_left.column() == 3:
        return special_comparison(source_left, source_right)
        # or perhaps
        val_left = source_left.data(some_role_returning_native_data_object)
        val_right = source_right.data(some_role_returning_native_data_object)
        return val_left.lessThan(val_right)
    return source_left.data() &lt; source_right.data()
    # or
    return QSortFIlterProxyModel.lessThan(source_left, source_right)
</code></pre>
]]></description><link>https://forum.qt.io/post/634010</link><guid isPermaLink="true">https://forum.qt.io/post/634010</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Wed, 23 Dec 2020 12:59:53 GMT</pubDate></item></channel></rss>