PDA

View Full Version : Problem with sorting QTreeView



Mohsin
28th April 2021, 09:58
After populating the QTreeView, I am using the following commands to sort the tree.

However, nothing changes in QTreeView.

Can anybody tell me what might be the issue? :)


ui->treeView->setSortingEnabled(true);
ui->treeView->sortByColumn(0, Qt::DescendingOrder);

ChrisW67
28th April 2021, 12:11
Can anybody tell me what might be the issue? :)
Perhaps they were already in order. Perhaps the model does not support sorting (https://doc.qt.io/qt-5/model-view-programming.html#sorting).
Hard to tell... we cannot see your code, your data, or what it looked like before and after sorting etc.

Mohsin
29th April 2021, 01:20
I am using the Simple Tree Model code example. https://het.as.utexas.edu/HET/Software/html/itemviews-simpletreemodel.html

And I have attached the screenshot of my data.13634

ChrisW67
29th April 2021, 05:20
You are using a basic implementation of a tree model. You will notice that it derives from QAbstractItemModel and that it does not override the QAbstractItemModel::sort() method. From the docs (https://doc.qt.io/qt-5/qabstractitemmodel.html#sort) you will see:


void QAbstractItemModel::sort(int column, Qt::SortOrder order = Qt::AscendingOrder)

Sorts the model by column in the given order.

The base class implementation does nothing.
No sorting ability is what you should expect from this model.

You could extend the custom tree model to provide sorting ability that the view can use directly (harder to get right), or you can insert a QSortFilterProxyModel between your model and the view. There are good examples in the class documentation for the proxy model approach.