|  | Home · Overviews · Examples |

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

The `QSqlTableModel` class provides an editable data model for a single database table. More...

Inherits `QSqlQueryModel`.

Inherited by `QSqlRelationalTableModel`.

## Detailed Description

The `QSqlTableModel` class provides an editable data model for a single database table.

`QSqlTableModel` is a high-level interface for reading and writing database records from a single table. It is build on top of the lower-level `QSqlQuery` and can be used to provide data to view classes such as `QTableView`. For example:

            QSqlTableModel *model = new QSqlTableModel;
            model->setTable("employee");
            model->setEditStrategy(QSqlTableModel::OnManualSubmit);
            model->select();
            model->removeColumn(0); // don't show the ID
            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 SQL table's name and the edit strategy, then we set up the labels displayed in the view header. The edit strategy dictates when the changes done by the user in the view are actually applied to the database. The possible values are `OnFieldChange`, `OnRowChange`, and `OnManualSubmit`.

`QSqlTableModel` can also be used to access a database programmatically, without binding it to a view:

            QSqlTableModel model;
            model.setTable("employee");
            QString name = model.record(4).value("name").toString();

The code snippet above extracts the `salary` field from record 4 in the result set of the query `SELECT * from employee`.

It is possible to set filters using `setFilter`, or modify the sort order using `setSort`. At the end, you must call `select` to populate the model with data.

The sql/tablemodel example illustrates how to use `QSqlTableModel` as the data source for a `QTableView`.

`QSqlTableModel` provides no direct support for foreign keys. Use the `QSqlRelationalTableModel` and QSqlRelationalDelegate if you want to resolve foreign keys.

The QSQLITE driver locks for updates until a select is finished. `QSqlTableModel` fetches data (QSqlQuery::fetchMore()) as needed; this may cause the updates to time out.

See also `QSqlRelationalTableModel`, `QSqlQuery`, Model/View Programming, Table Model Example, and Cached Table Example.