Important: Please read the Qt Code of Conduct -

Sorting data from QSqlQueryModel for a QTableView

  • Hi,

    I have QTableView filled from a QSqlQueryModel and i want to allow the user to sort the table by choosing an item in a QComboBox.

    I need a custom QSortFilterProxyModel but at this point, i'm totaly lost in the doc. I don't undertand how to reimplement the lessThan() function to match my needs.

    The data i need to sort are, for exemple, a level of priority (med, high,...), an order status (in progress,...).


  • in the lessThan you need to check 2 things: the column of the index (to determine if you are in the priority or status column) and once you know it it's just a list of ifs:

    bool MySortFilterProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const{
    if(source_left.column() == PriorityColumn){
    if( == "high") return false;
    if( == "high") return true;
    if( == "med") return false;
    if( == "med") return true;
    if( == "low") return false;
    if( == "low") return true;
    return false;
    else if(source_left.column() == StatusColumn){
    if( == "completed") return false;
    if( == "completed") return true;
    if( == "in progress") return false;
    if( == "in progress") return true;
    if( == "not started") return false;
    if( == "not started") return true;
    return false;
    return QSortFilterProxyModel::lessThan(source_left, source_right);

    The alternative is to assign a number to each valus (high=3, med=2, low=1 etc.) and put it in the Qt::UserRole of the model and then set the sort role but since you are using QSqlQueryModel I didn't think this solution was feasible

  • @VRonin

    Thanks, now i understand how to use it :)
    I'll use the ifs solution i think

Log in to reply