PySide6.QtSql.QSqlTableModel¶
- class QSqlTableModel¶
- The - QSqlTableModelclass provides an editable data model for a single database table.- Details- Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - QSqlTableModelis a high-level interface for reading and writing database records from a single table. It is built on top of the lower-level- QSqlQueryand 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.- QSqlTableModelcan 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 - salaryfield 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 - QSqlTableModelas the data source for a QTableView.- QSqlTableModelprovides no direct support for foreign keys. Use the- QSqlRelationalTableModeland- QSqlRelationalDelegateif you want to resolve foreign keys.- See also - QSqlRelationalTableModel- QSqlQueryTable Model Example Cached SQL Table- 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 - class EditStrategy¶
- This enum type describes which strategy to choose when editing values in the database. - Constant - Description - QSqlTableModel.EditStrategy.OnFieldChange - All changes to the model will be applied immediately to the database. - QSqlTableModel.EditStrategy.OnRowChange - Changes to a row will be applied when the user selects a different row. - QSqlTableModel.EditStrategy.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, - OnFieldChangewill behave like- OnRowChangefor newly inserted rows.- See also 
 - __init__([parent=None[, db=QSqlDatabase()]])¶
- Parameters:
- parent – - QObject
- db – - QSqlDatabase
 
 
 - Creates an empty - QSqlTableModeland sets the parent to- parentand the database connection to- db. If- dbis 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 the- rowis 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 in- recordand can be modified before they will be inserted.- beforeUpdate(row, record)¶
- Parameters:
- row – int 
- record – - QSqlRecord
 
 
 - This signal is emitted by - updateRowInTable()before the- rowis updated in the currently active database table with the values from- record.- Note that only values that are marked as generated will be updated. The generated flag can be set with - setGenerated()and checked with- isGenerated().- See also - database()¶
- Return type:
 
 - Returns the model’s database connection. - deleteRowFromTable(row)¶
- Parameters:
- row – int 
- Return type:
- bool 
 
 - Deletes the given - rowfrom 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 - trueif the row was deleted; otherwise returns- false.- 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 - recordat position- row. If- rowis negative, the record will be appended to the end. Calls- insertRows()and- setRecord()internally.- Returns - trueif the record could be inserted, otherwise false.- Changes are submitted immediately for - OnFieldChangeand- OnRowChange. 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 - valuesinto 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 - trueif the values could be inserted, otherwise false. Error information can be retrieved with- lastError().- See also - lastError()- insertRows()- isDirty()¶
- Return type:
- bool 
 
 - Returns - trueif the model contains modified values that have not been committed to the database, otherwise false.- isDirty(index)
- Parameters:
- index – - QModelIndex
- Return type:
- bool 
 
 - Returns - trueif the value at the index- indexis dirty, otherwise false. Dirty values are values that were modified in the model but not yet written into the database.- If - indexis invalid or points to a non-existing row, false is returned.- orderByClause()¶
- Return type:
- str 
 
 - Returns an SQL - ORDER BYclause based on the currently set sort order.- See also - Returns the primary key for the current table, or an empty - QSqlIndexif 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 given- rowof the currently active database table. The- recordparameter 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 as- setData()or- setRecord()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 returns- trueif successful; otherwise returns- false.- Note - Calling select() will revert any unsubmitted changes and remove any inserted columns. - See also - selectRow(row)¶
- Parameters:
- row – int 
- Return type:
- bool 
 
 - Refreshes - rowin 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 - trueif successful; otherwise returns- false.- See also - selectStatement()¶
- Return type:
- str 
 
 - Returns the SQL - SELECTstatement used internally to populate the model. The statement includes the filter and the- ORDER BYclause.- 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 - WHEREclause 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.- 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 - valuesto the- rowin the model. The source and target fields are mapped by field name, not by position in the record.- Note that the generated flags in - valuesare preserved to determine whether the corresponding fields are used when changes are submitted to the database. By default, it is set to- truefor all fields in a- QSqlRecord. You must set the flag to- falseusing- setGenerated(false) for any value in- values, to save changes back to the database.- For edit strategies - OnFieldChangeand- 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 - trueif all the values could be set; otherwise returns false.- See also - record()- editStrategy()- Sets the sort order for - columnto- order. This does not affect the current data, to refresh the data using the new sort order, call- select().- 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 - select()- setFilter()- lastError()- submitAll()¶
- Return type:
- bool 
 
 - Submits all pending changes and returns - trueon success. Returns- falseon 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 - OnManualSubmitmode, 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 - revertAll()- lastError()- 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 - rowin the currently active database table with the specified- values. Returns- trueif 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()