2

I have a QTreeWidget that I insert items in, and the user can select a column to sort it. As the items are being inserted, they just get appended to the end instead of having the sort being done automatically. If I click the header to switch between ascending/descending it will sort the current items.

I figured I could call sortItems() and use the column that is returned from sortColumn(), but I am unable to see how I can see if the user is doing an ascending or descending sort.

I'm not worried about the efficiency of this, so I don't want to wait until the insertions are done and then do the sort. I'd like a real-time sorted list.

Thanks!

staackuser2
  • 12,172
  • 4
  • 42
  • 40

2 Answers2

4

If your tree widget is called treeWidget, you should be able to call the header() method, which is from QTreeWidget's parent QTreeView, then sortIndicatorOrder() from the QHeaderView class:

treeWidget->header()->sortIndicatorOrder()

With this, you know the user's current sort order, and you can apply your sort on insert according to this.

2

I don't have a setup for testing but according to the documentation, this should cause sorting to occur as items are inserted.

...
treeWidget.sortByColumn(0, Qt::AscendingOrder); // column/order to sort by
treeWidget.setSortingEnabled(true);             // should cause sort on add

Qt recommends against doing this as there will be a performance cost and say that you should set sorting enabled after all the adds are completed. Hope this helps.

Arnold Spence
  • 21,942
  • 7
  • 74
  • 67
  • +1 for pointing out the sluggishness if you sort on insert. Note that this does not matter if you only add 1 item at a time and not in batches. – Arnab Datta Jul 31 '12 at 07:03