
We bake cookies in your browser for a better experience. Using this site means that you consent.Read More
TheQSqlTableModel class provides an editable data model for a single database table.More...
| Header: | #include <QSqlTableModel> |
| Inherits: | QSqlQueryModel |
| Inherited By: |
| enum | EditStrategy { OnFieldChange, OnRowChange, OnManualSubmit } |
| QSqlTableModel(QObject * parent = 0, QSqlDatabase db = QSqlDatabase()) | |
| virtual | ~QSqlTableModel() |
| QSqlDatabase | database() const |
| EditStrategy | editStrategy() const |
| int | fieldIndex(const QString & fieldName) const |
| QString | filter() const |
| bool | insertRecord(int row, const QSqlRecord & record) |
| bool | isDirty(const QModelIndex & index) const |
| QSqlIndex | primaryKey() const |
| virtual void | revertRow(int row) |
| virtual bool | select() |
| virtual void | setEditStrategy(EditStrategy strategy) |
| virtual void | setFilter(const QString & filter) |
| bool | setRecord(int row, const QSqlRecord & record) |
| virtual void | setSort(int column, Qt::SortOrder order) |
| virtual void | setTable(const QString & tableName) |
| QString | tableName() const |
| virtual void | clear() |
| virtual QVariant | data(const QModelIndex & index, int role = Qt::DisplayRole) const |
| virtual Qt::ItemFlags | flags(const QModelIndex & index) const |
| virtual QVariant | headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const |
| virtual bool | insertRows(int row, int count, const QModelIndex & parent = QModelIndex()) |
| virtual bool | removeColumns(int column, int count, const QModelIndex & parent = QModelIndex()) |
| virtual bool | removeRows(int row, int count, const QModelIndex & parent = QModelIndex()) |
| virtual int | rowCount(const QModelIndex & parent = QModelIndex()) const |
| virtual bool | setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) |
| virtual void | sort(int column, Qt::SortOrder order) |
| void | beforeDelete(int row) |
| void | beforeInsert(QSqlRecord & record) |
| void | beforeUpdate(int row, QSqlRecord & record) |
| void | primeInsert(int row, QSqlRecord & record) |
| virtual bool | deleteRowFromTable(int row) |
| QModelIndex | indexInQuery(const QModelIndex & item) const |
| virtual bool | insertRowIntoTable(const QSqlRecord & values) |
| virtual QString | orderByClause() const |
| virtual QString | selectStatement() const |
| void | setPrimaryKey(const QSqlIndex & key) |
| void | setQuery(const QSqlQuery & query) |
| virtual bool | updateRowInTable(int row, const QSqlRecord & values) |
TheQSqlTableModel 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-levelQSqlQuery and can be used to provide data to view classes such asQTableView. For example:
QSqlTableModel*model=newQSqlTableModel(parentObject, database); 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=newQTableView; 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 areOnFieldChange,OnRowChange, andOnManualSubmit.
QSqlTableModel 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 thesalary field from record 4 in the result set of the querySELECT * from employee.
It is possible to set filters usingsetFilter(), or modify the sort order usingsetSort(). At the end, you must callselect() to populate the model with data.
Thesql/tablemodel example illustrates how to useQSqlTableModel as the data source for aQTableView.
QSqlTableModel provides no direct support for foreign keys. Use theQSqlRelationalTableModel andQSqlRelationalDelegate if you want to resolve foreign keys.
See alsoQSqlRelationalTableModel,QSqlQuery,Model/View Programming,Table Model Example, andCached Table Example.
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 eithersubmitAll() orrevertAll() is called. |
Note: To prevent inserting only partly initialized rows into the database,OnFieldChange will behave likeOnRowChange for newly inserted rows.
See alsosetEditStrategy().
Creates an emptyQSqlTableModel and sets the parent toparent and the database connection todb. Ifdb is not valid, the default database connection will be used.
The default edit strategy isOnRowChange.
[virtual]QSqlTableModel::~QSqlTableModel()Destroys the object and frees any allocated resources.
[signal]void QSqlTableModel::beforeDelete(int row)This signal is emitted bydeleteRowFromTable() before therow is deleted from the currently active database table.
[signal]void QSqlTableModel::beforeInsert(QSqlRecord & record)This signal is emitted byinsertRowIntoTable() before a new row is inserted into the currently active database table. The values that are about to be inserted are stored inrecord and can be modified before they will be inserted.
[signal]void QSqlTableModel::beforeUpdate(int row,QSqlRecord & record)This signal is emitted byupdateRowInTable() before therow is updated in the currently active database table with the values fromrecord.
Note that only values that are marked as generated will be updated. The generated flag can be set withQSqlRecord::setGenerated() and checked withQSqlRecord::isGenerated().
See alsoQSqlRecord::isGenerated().
[virtual]void QSqlTableModel::clear()Reimplemented fromQSqlQueryModel::clear().
[virtual]QVariant QSqlTableModel::data(constQModelIndex & index,int role = Qt::DisplayRole) constReimplemented fromQAbstractItemModel::data().
See alsosetData().
Returns a pointer to the usedQSqlDatabase or 0 if no database was set.
[virtual protected]bool QSqlTableModel::deleteRowFromTable(int row)Deletes the givenrow from the currently active database table.
This is a low-level method that operates directly on the database and should not be called directly. UseremoveRow() orremoveRows() to delete values. The model will decide depending on its edit strategy when to modify the database.
Returns true if the row was deleted; otherwise returns false.
See alsoremoveRow() andremoveRows().
Returns the current edit strategy.
See alsosetEditStrategy().
Returns the index of the fieldfieldName, or -1 if no corresponding field exists in the model.
Returns the currently set filter.
See alsosetFilter() andselect().
[virtual]Qt::ItemFlags QSqlTableModel::flags(constQModelIndex & index) constReimplemented fromQAbstractItemModel::flags().
[virtual]QVariant QSqlTableModel::headerData(int section,Qt::Orientation orientation,int role = Qt::DisplayRole) constReimplemented fromQAbstractItemModel::headerData().
[protected]QModelIndex QSqlTableModel::indexInQuery(constQModelIndex & item) constReturns the index of the value in the database result set for the givenitem in the model.
The return value is identical toitem if no columns or rows have been inserted, removed, or moved around.
Returns an invalid model index ifitem is out of bounds or ifitem does not point to a value in the result set.
See alsoQSqlQueryModel::indexInQuery().
Inserts therecord afterrow. Ifrow is negative, the record will be appended to the end. CallsinsertRows() andsetRecord() internally.
Returns true if the row could be inserted, otherwise false.
See alsoinsertRows() andremoveRows().
[virtual protected]bool QSqlTableModel::insertRowIntoTable(constQSqlRecord & values)Inserts the valuesvalues into the currently active database table.
This is a low-level method that operates directly on the database and should not be called directly. UseinsertRow() andsetData() to insert values. The model will decide depending on its edit strategy when to modify the database.
Returns true if the values could be inserted, otherwise false. Error information can be retrieved withlastError().
See alsolastError(),insertRow(), andinsertRows().
[virtual]bool QSqlTableModel::insertRows(int row,int count, constQModelIndex & parent = QModelIndex())Reimplemented fromQAbstractItemModel::insertRows().
Insertscount empty rows at positionrow. Note thatparent must be invalid, since this model does not support parent-child relations.
Only one row at a time can be inserted when using theOnFieldChange orOnRowChange update strategies.
TheprimeInsert() signal will be emitted for each new row. Connect to it if you want to initialize the new row with default values.
Returns false if the parameters are out of bounds; otherwise returns true.
See alsoprimeInsert() andinsertRecord().
Returns true if the value at the indexindex is dirty, otherwise false. Dirty values are values that were modified in the model but not yet written into the database.
Ifindex is invalid or points to a non-existing row, false is returned.
[virtual protected]QString QSqlTableModel::orderByClause() constReturns an SQLORDER BY clause based on the currently set sort order.
See alsosetSort() andselectStatement().
Returns the primary key for the current table, or an emptyQSqlIndex if the table is not set or has no primary key.
See alsosetTable(),setPrimaryKey(), andQSqlDatabase::primaryIndex().
[signal]void QSqlTableModel::primeInsert(int row,QSqlRecord & record)This signal is emitted byinsertRows(), when an insertion is initiated in the givenrow of the currently active database table. Therecord parameter can be written to (since it is a reference), for example to populate some fields with default values.
[virtual]bool QSqlTableModel::removeColumns(int column,int count, constQModelIndex & parent = QModelIndex())Reimplemented fromQAbstractItemModel::removeColumns().
Removescount columns from theparent model, starting at indexcolumn.
Returns if the columns were successfully removed; otherwise returns false.
See alsoremoveRows().
[virtual]bool QSqlTableModel::removeRows(int row,int count, constQModelIndex & parent = QModelIndex())Reimplemented fromQAbstractItemModel::removeRows().
Removescount rows starting atrow. Since this model does not support hierarchical structures,parent must be an invalid model index.
Emits thebeforeDelete() signal before a row is deleted. When the edit strategy isOnManualSubmit signal emission is delayed untilsubmitAll() is called.
Returns true if all rows could be removed; otherwise returns false. Detailed error information can be retrieved usinglastError().
See alsoremoveColumns() andinsertRows().
[virtual slot]void QSqlTableModel::revert()Reimplemented fromQAbstractItemModel::revert().
This reimplemented slot is called by the item delegates when the user canceled editing the current row.
Reverts the changes if the model's strategy is set toOnRowChange. Does nothing for the other edit strategies.
UserevertAll() to revert all pending changes for theOnManualSubmit strategy orrevertRow() to revert a specific row.
See alsosubmit(),submitAll(),revertRow(), andrevertAll().
[slot]void QSqlTableModel::revertAll()Reverts all pending changes.
See alsorevert(),revertRow(), andsubmitAll().
[virtual]void QSqlTableModel::revertRow(int row)Reverts all changes for the specifiedrow.
See alsorevert(),revertAll(),submit(), andsubmitAll().
[virtual]int QSqlTableModel::rowCount(constQModelIndex & parent = QModelIndex()) constReimplemented fromQAbstractItemModel::rowCount().
[virtual]bool QSqlTableModel::select()Populates the model with data from the table that was set viasetTable(), using the specified filter and sort condition, and returns true if successful; otherwise returns false.
Note:Calling select() will revert any unsubmitted changes and remove any inserted columns.
See alsosetTable(),setFilter(), andselectStatement().
[virtual protected]QString QSqlTableModel::selectStatement() constReturns the SQLSELECT statement used internally to populate the model. The statement includes the filter and theORDER BY clause.
See alsofilter() andorderByClause().
[virtual]bool QSqlTableModel::setData(constQModelIndex & index, constQVariant & value,int role = Qt::EditRole)Reimplemented fromQAbstractItemModel::setData().
Sets the data for the itemindex for the rolerole tovalue. Depending on the edit strategy, the value might be applied to the database at once or cached in the model.
Returns true if the value could be set or false on error, for example ifindex is out of bounds.
See alsoeditStrategy(),data(),submit(),submitAll(), andrevertRow().
[virtual]void QSqlTableModel::setEditStrategy(EditStrategy strategy)Sets the strategy for editing values in the database tostrategy.
This will revert any pending changes.
See alsoeditStrategy() andrevertAll().
[virtual]void QSqlTableModel::setFilter(constQString & filter)Sets the current filter tofilter.
The filter is a SQLWHERE clause without the keywordWHERE (for example,name='Josephine').
If the model is already populated with data from a database, the model re-selects it with the new filter. Otherwise, the filter will be applied the next timeselect() is called.
See alsofilter(),select(),selectStatement(), andorderByClause().
[protected]void QSqlTableModel::setPrimaryKey(constQSqlIndex & key)Protected method that allows subclasses to set the primary key tokey.
Normally, the primary index is set automatically whenever you callsetTable().
See alsoprimaryKey() andQSqlDatabase::primaryIndex().
[protected]void QSqlTableModel::setQuery(constQSqlQuery & query)This function simply callsQSqlQueryModel::setQuery(query). You should normally not call it on aQSqlTableModel. Instead, usesetTable(),setSort(),setFilter(), etc., to set up the query.
See alsoselectStatement().
Sets the values at the specifiedrow to the values ofrecord. Returns true if all the values could be set; otherwise returns false.
See alsorecord().
[virtual]void QSqlTableModel::setSort(int column,Qt::SortOrder order)Sets the sort order forcolumn toorder. This does not affect the current data, to refresh the data using the new sort order, callselect().
See alsosort(),select(), andorderByClause().
[virtual]void QSqlTableModel::setTable(constQString & tableName)Sets the database table on which the model operates totableName. Does not select data from the table, but fetches its field information.
To populate the model with the table's data, callselect().
Error information can be retrieved withlastError().
See alsoselect(),setFilter(), andlastError().
[virtual]void QSqlTableModel::sort(int column,Qt::SortOrder order)Reimplemented fromQAbstractItemModel::sort().
Sorts the data bycolumn with the sort orderorder. This will immediately select data, usesetSort() to set a sort order without populating the model with data.
See alsosetSort(),select(), andorderByClause().
[virtual slot]bool QSqlTableModel::submit()Reimplemented fromQAbstractItemModel::submit().
This reimplemented slot is called by the item delegates when the user stopped editing the current row.
Submits the currently edited row if the model's strategy is set toOnRowChange orOnFieldChange. Does nothing for theOnManualSubmit strategy.
UsesubmitAll() to submit all pending changes for theOnManualSubmit strategy.
Returns true on success; otherwise returns false. UselastError() to query detailed error information.
On success the model will be repopulated. Any views presenting it will lose their selections.
See alsorevert(),revertRow(),submitAll(),revertAll(), andlastError().
[slot]bool QSqlTableModel::submitAll()Submits all pending changes and returns true on success. Returns false on error, detailed error information can be obtained withlastError().
On success the model will be repopulated. Any views presenting it will lose their selections.
Note: InOnManualSubmit mode, already submitted changes won't be cleared from the cache when submitAll() fails. This allows transactions to be rolled back and resubmitted again without losing data.
See alsorevertAll() andlastError().
Returns the name of the currently selected table.
[virtual protected]bool QSqlTableModel::updateRowInTable(int row, constQSqlRecord & values)Updates the givenrow in the currently active database table with the specifiedvalues. Returns true if successful; otherwise returns false.
This is a low-level method that operates directly on the database and should not be called directly. UsesetData() to update values. The model will decide depending on its edit strategy when to modify the database.
Note that only values that have the generated-flag set are updated. The generated-flag can be set withQSqlRecord::setGenerated() and tested withQSqlRecord::isGenerated().
See alsoQSqlRecord::isGenerated() andsetData().
© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.