QSqlTableModel

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

Inheritance diagram of PySide6.QtSql.QSqlTableModel

Inherited by: QSqlRelationalTableModel

Synopsis

Functions

Virtual functions

Slots

Signals

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:

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 , and OnManualSubmit .

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 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.

class PySide6.QtSql.QSqlTableModel([parent=None[, db=QSqlDatabase()]])
Parameters

Creates an empty QSqlTableModel and sets the parent to parent and the database connection to db. If db is not valid, the default database connection will be used.

The default edit strategy is OnRowChange .

PySide6.QtSql.QSqlTableModel.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() or revertAll() is called.

Note: To prevent inserting only partly initialized rows into the database, OnFieldChange will behave like OnRowChange for newly inserted rows.

PySide6.QtSql.QSqlTableModel.beforeDelete(row)
Parameters

row – int

PySide6.QtSql.QSqlTableModel.beforeInsert(record)
Parameters

recordPySide6.QtSql.QSqlRecord

PySide6.QtSql.QSqlTableModel.beforeUpdate(row, record)
Parameters
PySide6.QtSql.QSqlTableModel.database()
Return type

PySide6.QtSql.QSqlDatabase

Returns the model’s database connection.

PySide6.QtSql.QSqlTableModel.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 returns false.

See also

removeRow() removeRows()

PySide6.QtSql.QSqlTableModel.editStrategy()
Return type

EditStrategy

Returns the current edit strategy.

PySide6.QtSql.QSqlTableModel.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.

PySide6.QtSql.QSqlTableModel.filter()
Return type

str

Returns the currently set filter.

PySide6.QtSql.QSqlTableModel.insertRecord(row, record)
Parameters
Return type

bool

Inserts the record at position row. If row is negative, the record will be appended to the end. Calls insertRows() and setRecord() internally.

Returns true if the record could be inserted, otherwise false.

Changes are submitted immediately for OnFieldChange and OnRowChange . Failure does not leave a new row in the model.

See also

insertRows() removeRows() setRecord()

PySide6.QtSql.QSqlTableModel.insertRowIntoTable(values)
Parameters

valuesPySide6.QtSql.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 with lastError() .

See also

lastError() insertRow() insertRows()

PySide6.QtSql.QSqlTableModel.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.

PySide6.QtSql.QSqlTableModel.isDirty(index)
Parameters

indexPySide6.QtCore.QModelIndex

Return type

bool

Returns true if the value at the index index 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.

PySide6.QtSql.QSqlTableModel.orderByClause()
Return type

str

Returns an SQL ORDER BY clause based on the currently set sort order.

PySide6.QtSql.QSqlTableModel.primaryKey()
Return type

PySide6.QtSql.QSqlIndex

Returns the primary key for the current table, or an empty QSqlIndex if the table is not set or has no primary key.

PySide6.QtSql.QSqlTableModel.primaryValues(row)
Parameters

row – int

Return type

PySide6.QtSql.QSqlRecord

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

primaryKey()

PySide6.QtSql.QSqlTableModel.primeInsert(row, record)
Parameters
PySide6.QtSql.QSqlTableModel.revertAll()

Reverts all pending changes.

See also

revert() revertRow() submitAll()

PySide6.QtSql.QSqlTableModel.revertRow(row)
Parameters

row – int

Reverts all changes for the specified row.

See also

revert() revertAll() submit() submitAll()

PySide6.QtSql.QSqlTableModel.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 returns true if successful; otherwise returns false.

Note

Calling will revert any unsubmitted changes and remove any inserted columns.

PySide6.QtSql.QSqlTableModel.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 returns false.

See also

select()

PySide6.QtSql.QSqlTableModel.selectStatement()
Return type

str

Returns the SQL SELECT statement used internally to populate the model. The statement includes the filter and the ORDER BY clause.

PySide6.QtSql.QSqlTableModel.setEditStrategy(strategy)
Parameters

strategyEditStrategy

Sets the strategy for editing values in the database to strategy.

This will revert any pending changes.

PySide6.QtSql.QSqlTableModel.setFilter(filter)
Parameters

filter – str

Sets the current filter to filter.

The filter is a SQL WHERE clause without the keyword WHERE (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.

PySide6.QtSql.QSqlTableModel.setPrimaryKey(key)
Parameters

keyPySide6.QtSql.QSqlIndex

Protected method that allows subclasses to set the primary key to key.

Normally, the primary index is set automatically whenever you call setTable() .

PySide6.QtSql.QSqlTableModel.setRecord(row, record)
Parameters
Return type

bool

Applies values to the row 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 to true for all fields in a QSqlRecord . You must set the flag to false using setGenerated (false) for any value in values, to save changes back to the database.

For edit strategies OnFieldChange and OnRowChange , 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()

PySide6.QtSql.QSqlTableModel.setSort(column, order)
Parameters

Sets the sort order for column to order. This does not affect the current data, to refresh the data using the new sort order, call select() .

See also

sort() select() orderByClause()

PySide6.QtSql.QSqlTableModel.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() .

PySide6.QtSql.QSqlTableModel.submitAll()
Return type

bool

Submits all pending changes and returns true on success. Returns false on error, detailed error information can be obtained with lastError() .

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 fails. This allows transactions to be rolled back and resubmitted without losing data.

PySide6.QtSql.QSqlTableModel.tableName()
Return type

str

Returns the name of the currently selected table.

PySide6.QtSql.QSqlTableModel.updateRowInTable(row, values)
Parameters
Return type

bool

Updates the given row in the currently active database table with the specified values. 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. 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 with isGenerated() .

See also

isGenerated() setData()