Sorting QTableview items alphabetically!
-
wrote on 20 Nov 2017, 09:38 last edited by VRonin
In my QT C++ application when load button is clicked a database table column is displayed in a table view! I need to arrange the words when they are loaded in alphabetical order! How can I modify my code?
Dialog.h
ifndef DIALOG_H #define DIALOG_H #include <QDialog> class QSqlQueryModel; namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private slots: void on_searchMessages_clicked(); void on_pushButton_clicked(); private: Ui::Dialog *ui; QSqlQueryModel modal; };
Dialog.cpp
#include "dialog.h" #include "ui_dialog.h" #include <QSqlQuery> #include <QSqlQueryModel> #include "mainwindow.h" #include <QSqlDatabase> Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog), modal(new QSqlQueryModel(this)), { ui->setupUi(this); } Dialog::~Dialog() { delete ui; } void Dialog::on_pushButton_clicked() { { if(QSqlDatabase::contains("MyConnection")){ QSqlQuery qry(QSqlDatabase::database("MyConnection")); qry.prepare("Select UserName from User"); if(!qry.exec()) return; modal->setQuery(qry); ui->tableView->resizeColumnsToContents(); } QSqlDatabase::database("myconnection").close(); } } }
-
Did you get a chance to look at setSortingEnabled() and setSortColumn(..) APIs of QTableView. By default sorting is false. You can work with above APIs to achieve your requirement.
-
Did you get a chance to look at setSortingEnabled() and setSortColumn(..) APIs of QTableView. By default sorting is false. You can work with above APIs to achieve your requirement.
wrote on 20 Nov 2017, 09:59 last edited by@dheerendra I did ui->tableView->setSortingEnabled(true); yet the previous result is displayed
-
What is previous result ? I did not understand. Can u give more details ?
-
wrote on 20 Nov 2017, 10:13 last edited by VRonin
two options:
- put a
QSortFilterProxyModel
between your model and your view then callui->tableView->sort(0)
- change the query to
qry.prepare("Select UserName from User order by UserName");
- put a
-
two options:
- put a
QSortFilterProxyModel
between your model and your view then callui->tableView->sort(0)
- change the query to
qry.prepare("Select UserName from User order by UserName");
- put a
2/6