Qt C++ sorting TableView

1.3k Views Asked by At

Last time I was doing "computer service" as a project for studies. I wanted to display actual products in QTableView. It went well, it displays values from SQLite nicely. I'd like to sort values by clicking on header of the table (sort by column clicked).

Here's my code:

QSqlQueryModel * modal = new QSqlQueryModel();
QSqlQuery * qry = new QSqlQuery();
qry->prepare("Select * from products");
qry->exec();
modal->setQuery(*qry);
ui->tableView_2->setModel(modal);
ui->tableView_2->setSortingEnabled(true);
ui->tableView_2->show();

Could you help me?

1

There are 1 best solutions below

3
On

In the snipet above, your sections appear to be sort-able but not clickable.

To add that feature, you can simply call QHeaderView::setSectionsClickable().

QSqlQueryModel * modal = new QSqlQueryModel();
QSqlQuery * qry = new QSqlQuery();
qry->prepare("Select * from products");
qry->exec();
modal->setQuery(*qry);
ui->tableView_2->setModel(modal);
ui->tableView_2->setSortingEnabled(true);
ui->tableView_2->horizontalHeader()->setSectionsClickable(1);
ui->tableView_2->show();

This should do the trick, and allow you to simply click on the headers to sort by this column.