|  | Home · Overviews · Examples

# QSqlQueryModel Class Reference
[com.trolltech.qt.sql module]

The `QSqlQueryModel` class provides a read-only data model for SQL result sets. More...

Inherits `QAbstractTableModel`.

Inherited by `QSqlTableModel`.

## Detailed Description

The `QSqlQueryModel` class provides a read-only data model for SQL result sets.

`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 * 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 query `SELECT * from employee`. Assuming that `salary` is column 2, we can rewrite the last line as follows:

            int salary = model.data(model.index(4, 2)).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 sql/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 amount 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.