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,...).

    Thanks



  • 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(source_left.data().toString() == "high") return false;
    if(source_right.data().toString() == "high") return true;
    if(source_left.data().toString() == "med") return false;
    if(source_right.data().toString() == "med") return true;
    if(source_left.data().toString() == "low") return false;
    if(source_right.data().toString() == "low") return true;
    return false;
    }
    else if(source_left.column() == StatusColumn){
    if(source_left.data().toString() == "completed") return false;
    if(source_right.data().toString() == "completed") return true;
    if(source_left.data().toString() == "in progress") return false;
    if(source_right.data().toString() == "in progress") return true;
    if(source_left.data().toString() == "not started") return false;
    if(source_right.data().toString() == "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
    Hi,

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


Log in to reply
 

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