Sorting QTableview items alphabetically!
Solved
General and Desktop
-
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.
-
@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 ?