QTreeWidget - excluding top level items from sort
<p>I have a 2-level QTreeWidget. The top level only has one column and is just used for grouping the second level, which holds the actual multi-column data.</p>

<p>When I sort by clicking on a header (or any other way, really), I only want the second level to be sorted, as the top-level items have a fixed order set elsewhere in the app and shouldn't be affected.</p>

<p>How do I achieve this?</p>

<p>I found a solution based on the answer for <a href="http://stackoverflow.com/questions/33676893/qt-qtreewidget-disabling-interaction-for-a-single-column">this</a> question. Catch the sectionClicked signal and check if the clicked column is the first one. If so, force the static sort direction and then manually sort the children. Also needed a variable to manually track the sort direction for that column. Relevant code:</p>

<pre><code>self.lastSortDir = 1
self.treeWidget.header().sectionClicked.connect(self.headerSectionClicked)

def headerSectionClicked(self, colId):
    flip = {0:1, 1:0}
    if colId == 0:
        self.treeWidget.header().setSortIndicator(0,1)
        sortDir = flip[self.lastSortDir]
        for gId in self.groupWidgets:
            self.groupWidgets[gId].sortChildren(0, sortDir)
        self.lastSortDir = sortDir
</code></pre>

<p>This still isn't ideal for two main reasons:</p>

<ol>
<li><p>Every time you sort by the first column, two sorts will be performed, one to force the static direction and then another for the children. Could be an issue with larger data sets and is just inelegant.</p></li>
<li><p>The sort indicator for the first column will be stuck displaying the static sort direction instead of the actual direction the children are sorted by. Mostly just a cosmetic issue but it still triggers me.</p></li>
</ol>

<p>Not ideal, but considering everything else I tried didn't work at all, I'll take it for now. I wasted enough time on it already, and imperfect but working is better than perfect but not working.</p>

python sorting pyqt pyqt4 qtreewidget