QtableView setSortingEnabled  forcing sortByColumn()

  • I am using a QtableView (Qt5.9) and when I enable sorting using the setSortingEnabled (http://doc.qt.io/qt-4.8/qtableview.html#sortingEnabled-prop) 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 overwritte the sortByColumn() method and prevent the sorting there

    Same Question at StackOverflow(asked by me ):

  • Hi @mapuna

    Hmm, tableView->setSortingEnabled(true); sorts immediately. So, isn't it just enabled by pressing the appropiate column header by the user? I would think sorting is always possible but not done, by default. When the user presses a column header then sorting happens and the (sortingEnabled property is set to true). But no need to set it on your own.


  • @mapuna
    I faced this irritating issue too. I don't think setSortingEnabled() helps any --- as in, it actively does a SELECT call with ORDER BY column0 ---, and I don't believe you can change the behaviour.

    I only call QTableView.sortByColumn() when I am ready to pass in both the desired column and the sort order. I never call setSortingEnabled, and only the single desired SELECT ... ORDER BY ... is sent to the database.

    As a concomitant observation, I have found it very unobvious from both the (lack of) Qt documentation and the names of the function calls which view and/or model calls actually issue a SELECT statement and which do not. This is important to me, as I track all calls to the database. There are indeed times when you write a seemingly harmless piece of code which you think is just setting a variable but turns out to actually be accessing the database, just like setSortingEnabled. I have had to track them all down --- which I did by tracing the actual calls at the MySQL Server side --- and then see which ones can be avoided. I do not like the way the (otherwise excellent) Qt implementation has quite non-obvious, implicit calls to the database when you have no idea it is doing it, especially when you set something in the view.

  • Hi @JNBarchan

    You can influence the sorting. You will have to overwrite the operator< of the tablewigetitem. And you could tell it by a flag that you define to do nothing. But it's quite a hassle if you do it just as a workaround for that.


  • @m.sue said in QtableView setSortingEnabled forcing sortByColumn():

    Hi @JNBarchan

    You can influence the sorting. You will have to overwrite the operator< of the tablewigetitem


    And how would I do that given that I program in Python/PyQt? Plus, where is that documented, please?

    EDIT: Actually, I don't get that. The "comparison operator" should sort by the "sort column", whatever that is, and the problem is the QTableView has its own idea of what that is. It all works after QTableView.sortByColumn().

    I think the point/answer to the OP is that you simply do not want to do setSortingEnabled(), ever. And if I'm misunderstanding, and you do, you only want to do it after you have done QTableView.sortByColumn(column, order).

  • Hi @JNBarchan

    1. Nothing in the post says anything about PyQt.
    2. You could tell the items by a flag (that you define in a tableitem derived class) that do not want a sorting, no matter by what column that tableview thinks the sorting has to be done.


  • @m.sue
    Hang on, this is all coming back to me, I think. Let me write up a new post of what I believe my findings were, and we'll take it from there.

  • @m.sue
    For the "Python" bit, I meant this is a problem I too face, and I happen to be programming in Python/PyQt not C++. But never mind that.

    Here is what I believe I discovered:

    • QTableView.setSortingEnabled(True) is what is required to make the view's headers clickable. Unfortunately, and undocumented [hmm, it is in 5.9, I didn't think it used to be], this has a side-effect of issuing a SELECT statement to populate the model. IIRC, if this is the very first thing you do it issues SELECT ... FROM table with no ORDER BY at all.

    • QTableView.sortByColumn(column, direction) is what is required to set the sort column/direction, and it issues a SELECT ... FROM table ORDER BY <column> <direction>.

    • IIRC, if you call QTableView.setSortingEnabled(True) after you have called QTableView.sortByColumn(column, direction) it does know about the previous specification of column/direction, and issues its own SELECT ... FROM table ORDER BY <column> <direction>. This is better, but the problem is that you cannot suppress that second SELECT call, which is a waste, and unacceptable in my code.

    The upshot is, it is not possible to both choose a column/direction to sort by and to enable the QTableView's column headers without issuing 2 SELECT calls. Which is a nonsense.

    Assuming now that my findings are correct, would you be kind enough to offer some code --- or describe the necessary approach --- of whatever you are saying can achieve the objective but only issue a single SELECT ... ORDER BY ... call to the database, please? The "objective" is to start life --- i.e. before the user has a chance to click on a column header --- with clickable headers and the table populated sorted by some specified column with some specified direction?


    You can influence the sorting. You will have to overwrite the operator< of the tablewigetitem. And you could tell it by a flag that you define to do nothing.

    The point is --- at least in the case of a database model for the table view --- it's too late once you are look at table items/rows. It is the issuing of the whole SELECT statement which is the problem. I now see that the OP does not actually state what his model is, my whole query/interest is in the case where it is indeed a database, maybe his is too, and I at least should be really obliged for an answer to this....

  • Hi @JNBarchan

    Ok, if you need it to make the header columns clickable it's a nuisance. I did not remember it.

    I did not work with database derived tableviews, but just tableviews that I filled myself. And after I filled them they are static. Sorting was done by the tableview which asks the tableitems how to do it.

    Sorry, I have no experience about select statements that the tableview wants to deliver to the database and how to prohibit such statements.


  • @m.sue
    OK, thanks, if you have your own non-database, pre-populated model it doesn't really matter as you can control the sorting and it "takes no time" compared to a database call anyway. Yes, the issue being a problem is really for database model.

    I'd welcome any comment on this from a database-QTableView person...? :)

  • Hi @JNBarchan

    You probably use an SqlQueryModel whose void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) function is virtual. So you could influence whether it calls the database or not.


  • @m.sue
    But the problem is, I think, detecting when/where it's called. Mostly we do, of course, want to do sorts from the model to the database; the problem is that we need to call QTableView.setSortingEnabled() and QTableView.sortByColumn(), but we don't want them both to do a database call, at least something like not one after the other.

    OK, let me ask you (I am a Qt beginner), please: how can I robustly determine if QSqlQueryModel.sort() is being called from/as a result of QTableView.setSortingEnabled()? That might give me a start on a solution.

  • Hi @JNBarchan

    I would set a flag in a model (derived class instance) before I call setSortingEnabled(true). The flag will make the sort function do nothing. After the call setSortingEnabled(true) I would set the flag back. So the next call of the sort function makes it work by default.


  • @m.sue While workig with the QtableView I found out that , if I am not explicitly setting the tableView->setSortingEnabled(true); during model/view initializations then just clicking on the column header do not sorts the table.

    Its only when in init part I explicitly set sortingenabled flag then only the clicking on columns sorts the data.I am using Qt5.9, can you tell me what wrong can I be doing.

  • @mapuna
    I don't see you are doing anything "wrong". The whole point of the discussion above is that you do need to call tableView->setSortingEnabled(true) to enable column header sorting, and then as you have reported that will itself cause a sort to be executed at that point, just exactly as you said.

    Could you also kindly tell me, at least, what type of model you are using for the view --- is it a database (e.g. QSqlQuery), or is it your own in-memory data? Thank you.

  • @m.sue said in QtableView setSortingEnabled forcing sortByColumn():

    Hi @JNBarchan

    I would set a flag in a model (derived class instance) before I call setSortingEnabled(true). The flag will make the sort function do nothing. After the call setSortingEnabled(true) I would set the flag back. So the next call of the sort function makes it work by default.


    Let me see if I understand what you are suggesting, with the flag on the model. Here is some pseudo-C++/C# :) :

    DerivedSqlQueryModel() : QSqlQueryModel()
        bool doSort = true;
        override void sort(...)
            if (doSort)
    DerivedTableView(model) : QTableView(model)
        override void setSortingEnabled(bool enabled)
            model.doSort = false;
            model.doSort = true;

    Right? Thank you.

  • Lifetime Qt Champion


    Maybe QSortFilterProxyModel might be of interest ?

  • @JNBarchan May be I am not clear about my problem, below is the summary for my issue:

    • I want to enable sorting for QtableView so I call tableView->setSortingEnabled(true) in init
    • But beacuse of above my View/Table gets sorted by first column (calling tableView->setSortingEnabled(true) makes immediate
      call to sortbycolumn)
    • I do not want the sorting to be done by default , I want the tableView->setSortingEnabled(true) to just set the flag and not call the sortByColumn so when I view the table data is not sorted by any column instead the user can then choose which column to use for sorting
    • Is it possible that I do not need to tableView->setSortingEnabled(true) do in init just to enable the sorting in table/view ?Withouth setting this flag will clicking on header of column be able to sort the tableview?
    • I use Qt5.9 with Class myModel : public QAbstractTableModel

  • @mapuna
    On the contrary, I am saying: I do understand your issue, and yes it is a problem, for me too! I will try to be brief here, as we have already covered the detail if you read through above responses.

    It boils down to:

    • Yes, you do need to call tableView->setSortingEnabled(true) (somewhere) to enable sorting on the table.
    • No, it is not possible for tableView->setSortingEnabled(true) to just "set a flag" and not call sortByColumn(), it always calls that, unfortunately.

    Depending on your concrete implementation of QAbstractTableModel, it may or may not be an important issue that this extra sort call matters. In my case, since I am using QSqlQueryModel(), the unavoidable sort call does an actual call to a database SELECT, which is "slow" and therefore "bad". If your data is all in-memory, it probably doesn't actually matter that much, but it does to me.

    To resolve, what @m-sue is suggesting is that I (you?) override both QTableView::setSortingEnabled() and QAbstractItemModel::sort() along the lines shown in my pseudo-code above. The effect being that setSortingEnabled() will set a flag to cause sort() to do nothing while it is being called from setSortingEnabled() (which calls sortByColumn() which in turn calls sort()). The approach is "ugly", but seems to be what will work if you want to avoid the implicit sort() caused by setSortingEnabled(), which is what I want and seems to be what you want too.

  • @JNBarchan Thanks a lot for helping me, I just wanted to know I more thing (I ma newbie in QT ).As suggested by you to subcalss the QTableView, following is my question regarding the same:

    • When I make DerivedTableView(model) : QTableView(model), how can I add this new View in the QTCreator or do you suggest to add this new view programmatic ally or is there any other away to do so.

    • I have a tableview added in a complex layout in QtCreator and in the code I add models/delegates to it using
      ui->tableView_name->setModel(myProxy) etc... can I typecast ui->tableView_name at runtime to DerivedTableView is this also possible and then use DerivedTableView to set models/etc

    • I also could not find some working example where the Custom View is added in code and used if you can provide some reference it would help.

    Thanks in advance.

  • @mapuna
    I'm afraid I'm not the right person to ask really:

    • I don't use QtCreator, so I don't know.

    • I'm not sure just what you mean. You cannot just dynamically/run-time cast an object to another type/derived type because "you feel like it", when the object was constructed it must actually have been of the type you are casting to. So your QTableView must actually have been created as a DerivedTableView (including if that's done in QtCreator). But then wherever you can use a QTableView you can use your DerivedTableView, e.g. for setModel() call.

    • No example from me. I don't even use C++, I use Python! :(

    But I'm sure someone else can clarify the above.....

  • Lifetime Qt Champion


    1. http://doc.qt.io/qt-5/designer-using-custom-widgets.html
    2. You don't need to, just call setModel like you are doing currently
    3. Do you mean something like:
    MyView *view = new MyView;


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

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

    before running


    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.