QSqlTableModel Class
The QSqlTableModel class provides an editable data model for a single database table. More...
| Header: | #include <QSqlTableModel> |
| qmake: | QT += sql |
| Inherits: | QSqlQueryModel |
| Inherited By: |
Public Types
| enum | EditStrategy { OnFieldChange, OnRowChange, OnManualSubmit } |
Detailed Description
QSqlTableModel is a high-level interface for reading and writing database records from a single table. 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:
QSqlTableModel *model = new QSqlTableModel;
model->setTable("employee");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
QTableView *view = new QTableView;
view->setModel(model);
view->hideColumn(0); // don't show the ID
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");
model.select();
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.
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 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.
See also QSqlRelationalTableModel, QSqlQuery, Model/View Programming, Table Model Example, and Cached Table Example.
Member Type Documentation
enum QSqlTableModel::EditStrategy
This enum type describes which strategy to choose when editing values in the database.
| Constant | Value | Description |
|---|---|---|
QSqlTableModel::OnFieldChange | 0 | All changes to the model will be applied immediately to the database. |
QSqlTableModel::OnRowChange | 1 | Changes to a row will be applied when the user selects a different row. |
QSqlTableModel::OnManualSubmit | 2 | All changes will be cached in the model until either submitAll() or revertAll() is called. |
Note: To prevent inserting only partly initialized rows into the database, OnFieldChange will behave like OnRowChange for newly inserted rows.
See also setEditStrategy().