How to sort data by column in a table view if click to headerview[Solved]



  • @ Log cnn;
    QSqlQueryModel *modal=new QSqlQueryModel();
    QSqlQuery *qry=new QSqlQuery(cnn.mydb);
    qry->prepare("select *from log");
    qry->exec();
    modal->setQuery(*qry);
    ui->tableView->setModel(modal);
    ui->tableView->setAlternatingRowColors(true);
    ui->tableView->setSortingEnabled(true);
    ui->tableView->sortByColumn(4,Qt::AscendingOrder);//4 indicate the 4th column@

    I have a QTableView that is populated with a QSqlQueryModel. I am trying to sort the table based on which header is clicked, but nothing is happening when I press them.
    I used function sortByColumn()

    The problem is that the result is exactly the same,when i click the header the sorting is not working.
    

    What am I doing wrong?



  • Try to add this (for Qt 4):
    @ui->tableView->horizontalHeader()->setClickable(true);@
    Or, for Qt 5, this:
    @ui->tableView->horizontalHeader()->setSectionsClickable(true);@



  • Thanks...
    And also i solved my problem using QSortFilterProxyModel.

    Log cnn;
    QSqlQueryModel *modal=new QSqlQueryModel(this);
    QSqlQuery *qry=new QSqlQuery(cnn.mydb);
    qry->prepare("select *from AccessLog");
    qry->exec();
    modal->setQuery(*qry);

    QSortFilterProxyModel *m=new QSortFilterProxyModel(this);
    m->setDynamicSortFilter(true);
    m->setSourceModel(modal);
    ui->tableView->setModel(m);
    ui->tableView->setSortingEnabled(true);


Log in to reply
 

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