Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Detecting sort completed on QTableWidget



  • I need to do something after a user sorts a QTableWidget. I need to be able to detect when the table has been resorted. I tried detecting a click on the header, but that occurs before the sort. I need to do something after the sort is completed.

    Someone suggested overriding QTableWidget::sortItems, but since that is not virtual, my method doesn't override anything and doesn't get called.

    Another suggestion that I found was to replace the QSortFilterProxyModel that is used by the QTableWidget, but the methods to do so are private.

    I presumably could stop using QTableWidget and use QTableView instead, but that seems like a lot of work to get something that should be fairly simple. There must be a better way.

    I also tried catching the rowsMoved signal of the default model for QTableWidget (another suggestion I found). I was unable to catch the signal. Not sure why.

    Here is the code that I used to try to catch the signal.

    QAbstractItemModel * qModel = m_qUI.calendarTableWidget->model();
      connect(qModel,   SIGNAL(rowsMoved(const QModelIndex &, int, int, const QModelIndex, int)), this, SLOT(onCalendarRowsMoved(const QModelIndex &, int, int, const QModelIndex &, int)));
    

    To reiterate, I need to call a particular method of mine whenever a sort completes after someone clicks on the header of a QTableWidget.


  • Lifetime Qt Champion

    Hi,

    Can you explain what you need to do after the sorting applied ?



  • @james-b-s said in Detecting sort completed on QTableWidget:

    I need to call a particular method of mine whenever a sort completes

    connect(tableWidget->model(),&QAbstractItemModel::layoutChanged,this,&MyClass::onCalendarRowsMoved);

    You will need to change the signature of the slot though



  • My code had a typo in it. It really looks like this

     QAbstractItemModel * qModel = m_qUI.calendarTableWidget->model();
      connect(qModel,   SIGNAL(rowsMoved(const QModelIndex &, int, int, const QModelIndex &, int)), this, SLOT(onCalendarRowsMoved(const QModelIndex &, int, int, const QModelIndex &, int)));
    
    

    Still didn't work


  • Lifetime Qt Champion

    @james-b-s

    Works fine as @VRonin says

    for test i used

    connect(ui->tableWidget->model(), &QAbstractItemModel::layoutChanged,
        this, [](const QList<QPersistentModelIndex> &parents, QAbstractItemModel::LayoutChangeHint hint) {
        qDebug() << "sorted";
        });
    

    and it seems to work.

    Note he uses other signal than your code.



  • I am making related cells span together and I need to recalculate that when someone changes the sorting.



  • Thanks that worked