Search code examples
c++qtqt5qtableviewqsqlquery

QTableView c++ sort when header clicking


I need to sort a column in my table when I click to header of column. But now I can't, that's my table:

enter image description here

There is no action if I click to the header.

That's my c++ QT code:

    void showTable()
{
    connOpen();
    QSqlQueryModel * myModel=new QSqlQueryModel();
    QSqlQuery select;
    if (!select.exec("select * from tab")) {
        QMessageBox::critical(this, tr("Error"), select.lastError().text());
    }
    else {
        myModel->setQuery(select);
        ui->tableView->setModel(myModel);
    }
    connClose();
}

What should I do?


Solution

  • You have to do 2 things:

    • Enable the sortingEnabled property of the view so that the user can have control of the order by clicking on the horizontal header.

    • Use QSortFilterProxyModel to handle the order relationship.


    void showTable()
    {
        connOpen();
        QSqlQueryModel * myModel=new QSqlQueryModel(ui->tableView);
        QSqlQuery select;
        if (!select.exec("select * from tab")) {
            QMessageBox::critical(this, tr("Error"), select.lastError().text());
        }
        else {
            myModel->setQuery(select);
            QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(myModel); // create proxy
            proxyModel->setSourceModel(myModel);
            ui->tableView->setSortingEnabled(true); // enable sortingEnabled
            ui->tableView->setModel(proxyModel);
        }
        connClose();
    }