QSqlQueryModel Class
The QSqlQueryModel class provides a read-only data model for SQL result sets. More...
| Header: | #include <QSqlQueryModel> |
| qmake: | QT += sql |
| Inherits: | QAbstractTableModel |
| Inherited By: |
Detailed Description
QSqlQueryModel is a high-level interface for executing SQL statements and traversing the result set. It is built on top of the lower-level QSqlQuery and can be used to provide data to view classes such as QTableView. For example:
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT name, salary FROM employee");
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
QTableView *view = new QTableView;
view->setModel(model);
view->show();
We set the model's query, then we set up the labels displayed in the view header.
QSqlQueryModel can also be used to access a database programmatically, without binding it to a view:
QSqlQueryModel model;
model.setQuery("SELECT name, salary FROM employee");
int salary = model.record(4).value("salary").toInt();
The code snippet above extracts the salary field from record 4 in the result set of the SELECT query. Since salary is the 2nd column (or column index 1), we can rewrite the last line as follows:
int salary = model.data(model.index(4, 1)).toInt();
The model is read-only by default. To make it read-write, you must subclass it and reimplement setData() and flags(). Another option is to use QSqlTableModel, which provides a read-write model based on a single database table.
The querymodel example illustrates how to use QSqlQueryModel to display the result of a query. It also shows how to subclass QSqlQueryModel to customize the contents of the data before showing it to the user, and how to create a read-write model based on QSqlQueryModel.
If the database doesn't return the number of selected rows in a query, the model will fetch rows incrementally. See fetchMore() for more information.
See also QSqlTableModel, QSqlRelationalTableModel, QSqlQuery, Model/View Programming, and Query Model Example.