Nominate our 2022 Qt Champions!

Sorting qtablewidget using proxymodel

  • Hello!

    I have a qtablewidget which has a slot connected to it which is activated by the signal currentCellChanged. The slot loads information based on the cell row which is clicked.

    Now I would like sort my rows when I click on the horizontal header items. So I tried setSortingEnabled(true) after populating the qtablewidget with items. This works, but after sorting I still want the slot connected correctly, so I need to know the original row index of the clicked row.

    I read the documentation of qsortfilterproxymodel and I think this is the way to go. However I'm confused about the implementation since I did not use a table model or tableview. (Is it correct that qtablewidget is a tableview?)

    Can I set the proxymodel up as follows and how do I create the model from my qtablewidget?

    MyItemModel *sourceModel = new MyItemModel(this);
    QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);

  • Lifetime Qt Champion


    You can't replace a QTableWidget's model so you'll have to go with QTableView + QStandardItemModel (or custom model you need) + QSortFilterProxyModel

    Out of curiosity, why do you need to stay at the same row after you have your data sorted ?

  • I figured out that the best solution indeed is to go with QTableView, QStandardItemModel and a QSortFilterProxyModel, because QTableWidget uses it's own internal model. Unfortunately, I already had a lot of slots etc connected to the table, so it was a little invconvenient to switch to a QTableView.

    I solved my issues by adding an extra column with the original row numbers, which I hid. Then I referred to this row indirectly. It worked, although it's not an elegant solution.

  • Lifetime Qt Champion

    I'm still curious about that fixed row when sorting

  • I’m still curious about that fixed row when sorting

    I see millions of reasons. Assume row has a file name you clicked in file manager sorted by extension. Then you sort by name to see all the files with the same name and different extension.

Log in to reply