0

I am using a QTableView and when I enable sorting using the setSortingEnabled there is an immediate call to the sortByColumn(), but I do not want this as this sorts my table by default 1st column.

  • I want just to enable sorting and not to force sorting when enabling
  • Is there a way to avoid the sortByColumn() call?
  • Or how can I overwrite the sortByColumn() method and prevent the sorting there?
cbuchart
  • 10,847
  • 9
  • 53
  • 93
mapuna
  • 53
  • 1
  • 5
  • Why do not you call that function when you want it to be ordered and not before? – eyllanesc Nov 09 '17 at 04:23
  • @eyllanesc as far as I have gathered to enable sorting for the QTableView we need to set the setSortingEnabled to true I am doing this in my init function when setting up the model/view/delegates for my view. – mapuna Nov 09 '17 at 04:50
  • @eyllanesc it would be helpful if you can suggest where can I set the flag setSortingEnabled so that I am able to do sorting by clicking on column headers. – mapuna Nov 09 '17 at 04:51
  • Okay, I got it, are you using Qt4 or Qt5? – eyllanesc Nov 09 '17 at 04:55
  • @eyllanesc I am using Qt5.9 – mapuna Nov 09 '17 at 05:01
  • I just tried and even if I enabled the property sortingEnabled to True the table is not sorted, I find it strange what it says. – eyllanesc Nov 09 '17 at 05:02
  • @eyllanesc can you try to use a model derived from QAbstractTableModel , and then try the same, I found this answer useful : http://www.qtcentre.org/threads/467-QTableView-sorting for your issue – mapuna Nov 09 '17 at 05:21
  • You must provide a MVCE, you could share a project to analyze it. – eyllanesc Nov 09 '17 at 05:24

2 Answers2

0

There is a possible work-around for the above problem as has been suggestted in the Qt Forums where I asked the similar question https://forum.qt.io/topic/84870/qtableview-setsortingenabled-forcing-sortbycolumn

mapuna
  • 53
  • 1
  • 5
0

You could set default sorting column to -1 by QHeaderView::setSortIndicator like this

yourTableView->horizontalHeader()->setSortIndicator(-1, Qt::AscendingOrder);

before running

yourTableView->setSortingEnabled(true);

because QTableView::setSortingEnabled uses QHeaderView::sortIndicatorOrder and QHeaderView::sortIndicatorSection to identify by which column should model be sorted.

Note that documentation of QHeaderView::setSortIndicator tells that not all models support setting sort column to -1 and may even crash in this case.