Search code examples
qt4qtableviewqt4.7qstandarditemmodel

Custom sorting method of QTableView?


How can I setup custom sorting method for a QTableView , or for the model ? (Which function should I re-implement)

The default sorting algorithm are for strings , I want a number sorting method for some specific column.

Thanks.


Solution

  • You should use QSortFilterProxyModel. You should reimplement lessThan method. Then you have to set sourceModel for your proxy model, and set your proxy model as model for your view

    class MyProxyModel: public QSortFilterProxyModel
    {
    protected:
         bool   lessThan ( const QModelIndex & left, const QModelIndex & right ) const
         {
             // your sorting rules
         }
    };
    
    // ... somewhere where your view is accessible
    MyProxyModel * m = new MyProxyModel();
    m->setSourceModel(yourModel);
    yourView->setModel(m);