Problem sorting TableView



  • Hello everyone,
    I'm tring to sort my data filled in a QTableView. Data are the result of a query.
    For that, I've proceed like below :
    @QSqlQueryModel *modelAb = new QSqlQueryModel(this);
    modelAb ->setQuery(query, dbConnexion);
    while(modelAb->canFetchMore())
    modelAb->fetchMore();

    QSortFilterProxyModel * mSortFilterModel = new QSortFilterProxyModel(this);
    mSortFilterModel->setDynamicSortFilter(true);
    mSortFilterModel->setSourceModel(modelAb);
    tabAbonne->setModel(mSortFilterModel);
    tabAbonne->setSortingEnabled(true);@
    My problem is that for some columns, sorting works fine but for the other is not working.
    Can anyone help me to resolve this problem.
    Best regards.



  • You'll have to be a bit more specific. "Some columns"? What kind of columns does it work for, and what kind of columns doesn't it work for?



  • Trivial question: could it be that sorting thru a column does not change the output because data is already sorted also on such column? Example:

    |column 1 | column 2 |
    | A | B |
    | C | D |

    Here sorting by column1 or column2 produces the same result.
    Moreover, what is the aim of the while loop?

    @while(modelAb->canFetchMore())
    modelAb->fetchMore();@

    instead of a simpler and more efficient (from a database perspective)

    @modelAb->select();@

    [EDIT: table mode for table, Volker]



  • The easiest way, except to improve the select, is to redefine the operator<() of the QAbstractItem, but course here it's not possible.

    Setting simply the QSortFilterProxyModel() makes no big advantage than the normal sorting of the QTableView (using SortingRole). You need to inherit the class and redefine at least the function:
    @virtual bool lessThan ( const QModelIndex & left, const QModelIndex & right ) const@

    Because of course date/time and file names aren't good candidates for the alphanumerical sorting.



  • Many thanks for replying.
    The sort works for columns of type Integer, QString and QDate. But it no works for a QDateTime column.
    I've tried to re-implement lessThen method but I've no issu. Can anyone help me for that because I've searched a lot and it seems that it is ths unique solution to resolve this problem.
    Best regards.



  • What is your current code? Did you inherit the QSortFilterProxyModel ?



  • Did you try setting the right sortRole? I would set it to Qt::EditRole by default, as the Qt::DisplayRole is only a textual representation of the data, but not the actual data itself.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.