QSqlTableModel Class▲
-
Header: QSqlTableModel
-
CMake:
find_package(Qt6 REQUIRED COMPONENTS Sql)
target_link_libraries(mytarget PRIVATE Qt6::Sql)
-
qmake: QT += sql
-
Inherits: QSqlQueryModel
-
Inherited By: QSqlRelationalTableModel
-
Group: QSqlTableModel is part of Database Classes
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-&
gt;setTable("employee"
);
model-&
gt;setEditStrategy(QSqlTableModel::
OnManualSubmit);
model-&
gt;select();
model-&
gt;setHeaderData(0
, Qt::
Horizontal, tr("Name"
));
model-&
gt;setHeaderData(1
, Qt::
Horizontal, tr("Salary"
));
QTableView *
view =
new
QTableView;
view-&
gt;setModel(model);
view-&
gt;hideColumn(0
); // don't show the ID
view-&
gt;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