- class QSqlTableModel¶
The
QSqlTableModel
class provides an editable data model for a single database table. More…Inherited by:
QSqlRelationalTableModel
Synopsis¶
Methods¶
def
__init__()
def
database()
def
editStrategy()
def
fieldIndex()
def
filter()
def
insertRecord()
def
isDirty()
def
primaryKey()
def
primaryValues()
def
setPrimaryKey()
def
setRecord()
def
tableName()
Virtual methods¶
def
orderByClause()
def
revertRow()
def
select()
def
selectRow()
def
setFilter()
def
setSort()
def
setTable()
Slots¶
def
revertAll()
def
submitAll()
Signals¶
def
beforeDelete()
def
beforeInsert()
def
beforeUpdate()
def
primeInsert()
Note
This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE
Detailed Description¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
QSqlTableModel
is a high-level interface for reading and writing database records from a single table. It is built on top of the lower-levelQSqlQuery
and can be used to provide data to view classes such as QTableView. For example:model = QSqlTableModel() model.setTable("employee") model.setEditStrategy(QSqlTableModel.OnManualSubmit) model.select() model.setHeaderData(0, Qt.Horizontal, tr("Name")) model.setHeaderData(1, Qt.Horizontal, tr("Salary")) view = 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
, andOnManualSubmit
.QSqlTableModel
can also be used to access a database programmatically, without binding it to a view:model = QSqlTableModel() model.setTable("employee") model.select() salary = model.record(4).value("salary").toInt()
The code snippet above extracts the
salary
field from record 4 in the result set of the querySELECT * from employee
.It is possible to set filters using
setFilter()
, or modify the sort order usingsetSort()
. At the end, you must callselect()
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 theQSqlRelationalTableModel
andQSqlRelationalDelegate
if you want to resolve foreign keys.See also
QSqlRelationalTableModel
QSqlQuery
Table Model Example Cached SQL Table- class EditStrategy¶
This enum type describes which strategy to choose when editing values in the database.
Constant
Description
QSqlTableModel.OnFieldChange
All changes to the model will be applied immediately to the database.
QSqlTableModel.OnRowChange
Changes to a row will be applied when the user selects a different row.
QSqlTableModel.OnManualSubmit
All changes will be cached in the model until either
submitAll()
orrevertAll()
is called.Note: To prevent inserting only partly initialized rows into the database,
OnFieldChange
will behave likeOnRowChange
for newly inserted rows.See also
- __init__([parent=None[, db=QSqlDatabase()]])¶
- Parameters:
parent –
QObject
db –
QSqlDatabase
Creates an empty
QSqlTableModel
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 is
OnRowChange
.- beforeDelete(row)¶
- Parameters:
row – int
This signal is emitted by
deleteRowFromTable()
before therow
is deleted from the currently active database table.- beforeInsert(record)¶
- Parameters:
record –
QSqlRecord
This signal is emitted by
insertRowIntoTable()
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.- beforeUpdate(row, record)¶
- Parameters:
row – int
record –
QSqlRecord
This signal is emitted by
updateRowInTable()
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 with
setGenerated()
and checked withisGenerated()
.See also
- database()¶
- Return type:
Returns the model’s database connection.
- deleteRowFromTable(row)¶
- Parameters:
row – int
- Return type:
bool
Deletes the given
row
from the currently active database table.This is a low-level method that operates directly on the database and should not be called directly. Use removeRow() or
removeRows()
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 returnsfalse
.See also
removeRows()
- editStrategy()¶
- Return type:
Returns the current edit strategy.
See also
- fieldIndex(fieldName)¶
- Parameters:
fieldName – str
- Return type:
int
Returns the index of the field
fieldName
, or -1 if no corresponding field exists in the model.- filter()¶
- Return type:
str
Returns the currently set filter.
See also
- insertRecord(row, record)¶
- Parameters:
row – int
record –
QSqlRecord
- Return type:
bool
Inserts the
record
at positionrow
. Ifrow
is negative, the record will be appended to the end. CallsinsertRows()
andsetRecord()
internally.Returns
true
if the record could be inserted, otherwise false.Changes are submitted immediately for
OnFieldChange
andOnRowChange
. Failure does not leave a new row in the model.See also
insertRows()
removeRows()
setRecord()
- insertRowIntoTable(values)¶
- Parameters:
values –
QSqlRecord
- Return type:
bool
Inserts the values
values
into the currently active database table.This is a low-level method that operates directly on the database and should not be called directly. Use insertRow() and
setData()
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 also
lastError()
insertRows()
- isDirty()¶
- Return type:
bool
This is an overloaded function.
Returns
true
if the model contains modified values that have not been committed to the database, otherwise false.- isDirty(index)
- Parameters:
index –
QModelIndex
- Return type:
bool
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.If
index
is invalid or points to a non-existing row, false is returned.- orderByClause()¶
- Return type:
str
Returns an SQL
ORDER BY
clause based on the currently set sort order.See also
Returns the primary key for the current table, or an empty
QSqlIndex
if the table is not set or has no primary key.See also
- primaryValues(row)¶
- Parameters:
row – int
- Return type:
Returns a record containing the fields represented in the primary key set to the values at
row
. If no primary key is defined, the returned record will contain all fields.See also
- primeInsert(row, record)¶
- Parameters:
row – int
record –
QSqlRecord
This signal is emitted by
insertRows()
, 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 and set the generated flags of the fields. Do not try to edit the record via other means such assetData()
orsetRecord()
while handling this signal.- revertAll()¶
Reverts all pending changes.
See also
revert()
revertRow()
submitAll()
- revertRow(row)¶
- Parameters:
row – int
Reverts all changes for the specified
row
.See also
revert()
revertAll()
submit()
submitAll()
- select()¶
- Return type:
bool
Populates the model with data from the table that was set via
setTable()
, using the specified filter and sort condition, and returnstrue
if successful; otherwise returnsfalse
.Note
Calling select() will revert any unsubmitted changes and remove any inserted columns.
See also
- selectRow(row)¶
- Parameters:
row – int
- Return type:
bool
Refreshes
row
in the model with values from the database table row matching on primary key values. Without a primary key, all column values must match. If no matching row is found, the model will show an empty row.Returns
true
if successful; otherwise returnsfalse
.See also
- selectStatement()¶
- Return type:
str
Returns the SQL
SELECT
statement used internally to populate the model. The statement includes the filter and theORDER BY
clause.See also
- setEditStrategy(strategy)¶
- Parameters:
strategy –
EditStrategy
Sets the strategy for editing values in the database to
strategy
.This will revert any pending changes.
See also
- setFilter(filter)¶
- Parameters:
filter – str
Sets the current filter to
filter
.The filter is a SQL
WHERE
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 time
select()
is called.See also
Protected method that allows subclasses to set the primary key to
key
.Normally, the primary index is set automatically whenever you call
setTable()
.See also
- setRecord(row, record)¶
- Parameters:
row – int
record –
QSqlRecord
- Return type:
bool
Applies
values
to therow
in the model. The source and target fields are mapped by field name, not by position in the record.Note that the generated flags in
values
are preserved to determine whether the corresponding fields are used when changes are submitted to the database. By default, it is set totrue
for all fields in aQSqlRecord
. You must set the flag tofalse
usingsetGenerated
(false) for any value invalues
, to save changes back to the database.For edit strategies
OnFieldChange
andOnRowChange
, a row may receive a change only if no other row has a cached change. Changes are submitted immediately. Submitted changes are not reverted upon failure.Returns
true
if all the values could be set; otherwise returns false.See also
record()
editStrategy()
Sets the sort order for
column
toorder
. This does not affect the current data, to refresh the data using the new sort order, callselect()
.See also
sort()
select()
orderByClause()
- setTable(tableName)¶
- Parameters:
tableName – str
Sets the database table on which the model operates to
tableName
. Does not select data from the table, but fetches its field information.To populate the model with the table’s data, call
select()
.Error information can be retrieved with
lastError()
.See also
- submitAll()¶
- Return type:
bool
Submits all pending changes and returns
true
on success. Returnsfalse
on error, detailed error information can be obtained withlastError()
.In
OnManualSubmit
, on success the model will be repopulated. Any views presenting it will lose their selections.Note: In
OnManualSubmit
mode, already submitted changes won’t be cleared from the cache when submitAll() fails. This allows transactions to be rolled back and resubmitted without losing data.See also
- tableName()¶
- Return type:
str
Returns the name of the currently selected table.
- updateRowInTable(row, values)¶
- Parameters:
row – int
values –
QSqlRecord
- Return type:
bool
Updates the given
row
in the currently active database table with the specifiedvalues
. Returnstrue
if successful; otherwise returnsfalse
.This is a low-level method that operates directly on the database and should not be called directly. Use
setData()
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 with
setGenerated()
and tested withisGenerated()
.See also
isGenerated()
setData()