Overview | Package | Class | Tree | Deprecated | Index | Help
Qt Jambi Home |
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

## com.trolltech.qt.sql
Class QSqlTableModel

    java.lang.Object
      com.trolltech.qt.QSignalEmitter
          com.trolltech.qt.QtJambiObject
              com.trolltech.qt.core.QObject
                  com.trolltech.qt.core.QAbstractItemModel
                      com.trolltech.qt.gui.QAbstractTableModel
                          com.trolltech.qt.sql.QSqlQueryModel
                              com.trolltech.qt.sql.QSqlTableModel

All Implemented Interfaces:
  QtJambiInterface

Direct Known Subclasses:
  QSqlRelationalTableModel

    public class QSqlTableModel

extends QSqlQueryModel

The `QSqlTableModel` 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-level `QSqlQuery` and can be used to provide data to view classes such as `QTableView`. For example:

            QSqlTableModel *model = new QSqlTableModel;
            model->setTable("employee");
            model->setEditStrategy(QSqlTableModel::OnManualSubmit);
            model->select();
            model->removeColumn(0); // don't show the ID
            model->setHeaderData(0, Qt::Horizontal, tr("Name"));
            model->setHeaderData(1, Qt::Horizontal, tr("Salary"));

            QTableView *view = new QTableView;
            view->setModel(model);
            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:

            QSqlTableModel model;
            model.setTable("employee");
            QString name = model.record(4).value("name").toString();

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

The QSQLITE driver locks for updates until a select is finished. `QSqlTableModel` fetches data (QSqlQuery::fetchMore()) as needed; this may cause the updates to time out.

See Also:
  `QSqlRelationalTableModel`, `QSqlQuery`, Model/View Programming, `Model Example`, Cached Table Example

Nested Class Summary
`static class` | `QSqlTableModel.EditStrategy` This enum type describes which strategy to choose when editing values in the database.

Nested classes/interfaces inherited from class com.trolltech.qt.QSignalEmitter
`QSignalEmitter.AbstractSignal, QSignalEmitter.Signal0, QSignalEmitter.Signal1<A>, QSignalEmitter.Signal2<A,B>, QSignalEmitter.Signal3<A,B,C>, QSignalEmitter.Signal4<A,B,C,D>, QSignalEmitter.Signal5<A,B,C,D,E>, QSignalEmitter.Signal6<A,B,C,D,E,F>, QSignalEmitter.Signal7<A,B,C,D,E,F,G>, QSignalEmitter.Signal8<A,B,C,D,E,F,G,H>, QSignalEmitter.Signal9<A,B,C,D,E,F,G,H,I>`

Field Summary
`QSignalEmitter.Signal1<java.lang.Integer>` | `beforeDelete` This signal is emitted before the `row` is deleted.
`QSignalEmitter.Signal1<QSqlRecord>` | `beforeInsert` This signal is emitted before a new row is inserted.
`QSignalEmitter.Signal2<java.lang.Integer,QSqlRecord>` | `beforeUpdate` This signal is emitted before the `row` is updated with the values from `record`.
`QSignalEmitter.Signal2<java.lang.Integer,QSqlRecord>` | `primeInsert` This signal is emitted when an insertion is initiated in the given `row`.

Fields inherited from class com.trolltech.qt.core.QAbstractItemModel
`dataChanged, headerDataChanged, layoutAboutToBeChanged, layoutChanged`

Constructor Summary
`QSqlTableModel()` Equivalent to `QSqlTableModel`(0, QSqlDatabase()).
`QSqlTableModel(QObject parent)` Equivalent to `QSqlTableModel`(`parent`, QSqlDatabase()).
`QSqlTableModel(QObject parent, QSqlDatabase db)` Creates an empty `QSqlTableModel` and sets the parent to `parent` and the database connection to `db`.

Method Summary
`void` | `clear()` This function is reimplemented for internal reasons.
`java.lang.Object` | `data(QModelIndex idx, int role)` This function is reimplemented for internal reasons.
`QSqlDatabase` | `database()` Returns a pointer to the used `QSqlDatabase` or 0 if no database was set.
`protected boolean` | `deleteRowFromTable(int row)` Deletes the given `row` from the currently active database table.
`QSqlTableModel.EditStrategy` | `editStrategy()` Returns the current edit strategy.
`int` | `fieldIndex(java.lang.String fieldName)` Returns the index of the field `fieldName`.
`java.lang.String` | `filter()` Returns the currently set filter.
`Qt.ItemFlags` | `flags(QModelIndex index)` This function is reimplemented for internal reasons.
`static QSqlTableModel` | `fromNativePointer(QNativePointer nativePointer)` This function returns the QSqlTableModel instance pointed to by nativePointer
`java.lang.Object` | `headerData(int section, Qt.Orientation orientation, int role)` This function is reimplemented for internal reasons.
`protected QModelIndex` | `indexInQuery(QModelIndex item)` Returns the index of the value in the database result set for the given `item` in the model.
`boolean` | `insertRecord(int row, QSqlRecord record)` Inserts the `record` after `row`.
`protected boolean` | `insertRowIntoTable(QSqlRecord values)` Inserts the values `values` into the currently active database table.
`boolean` | `insertRows(int row, int count, QModelIndex parent)` Inserts `count` empty rows at position `row`.
`boolean` | `isDirty(QModelIndex index)` Returns true if the value at the index `index` is dirty, otherwise false.
`protected java.lang.String` | `orderByClause()` Returns an SQL `ORDER BY` clause based on the currently set sort order.
`QSqlIndex` | `primaryKey()` Returns the primary key for the current table, or an empty `QSqlIndex` if the table is not set or has no primary key.
`boolean` | `removeColumns(int column, int count, QModelIndex parent)` Removes `count` columns from the `parent` model, starting at index `column`.
`boolean` | `removeRows(int row, int count, QModelIndex parent)` Removes `count` rows starting at `row`.
`void` | `revert()` This reimplemented slot is called by the item delegates when the user canceled editing the current row.
`void` | `revertAll()` Reverts all pending changes.
`void` | `revertRow(int row)` Reverts all changes for the specified `row`.
`int` | `rowCount(QModelIndex parent)` This function is reimplemented for internal reasons.
`boolean` | `select()` 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.
`protected java.lang.String` | `selectStatement()` Returns the SQL `SELECT` statement used internally to populate the model.
`boolean` | `setData(QModelIndex index, java.lang.Object value, int role)` Sets the data for the item `index` for the role `role` to `value`.
`void` | `setEditStrategy(QSqlTableModel.EditStrategy strategy)` Sets the strategy for editing values in the database to `strategy`.
`void` | `setFilter(java.lang.String filter)` Sets the current filter to `filter`.
`protected void` | `setPrimaryKey(QSqlIndex key)` Protected method that allows subclasses to set the primary key to `key`.
`void` | `setQuery(QSqlQuery query)` This function simply calls QSqlQueryModel::setQuery(`query`).
`boolean` | `setRecord(int row, QSqlRecord record)` Sets the values at the specified `row` to the values of `record`.
`void` | `setSort(int column, Qt.SortOrder order)` Sets the sort order for `column` to `order`.
`void` | `setTable(java.lang.String tableName)` Sets the database table on which the model operates to `tableName`.
`void` | `sort(int column, Qt.SortOrder order)` Sorts the data by `column` with the sort order `order`.
`boolean` | `submit()` This reimplemented slot is called by the item delegates when the user stopped editing the current row.
`boolean` | `submitAll()` Submits all pending changes and returns true on success.
`java.lang.String` | `tableName()` Returns the name of the currently selected table.
`protected boolean` | `updateRowInTable(int row, QSqlRecord values)` Updates the given `row` in the currently active database table with the specified `values`.

Methods inherited from class com.trolltech.qt.sql.QSqlQueryModel
`canFetchMore, columnCount, fetchMore, insertColumns, lastError, query, queryChange, record, record, setHeaderData, setLastError, setQuery, setQuery`

Methods inherited from class com.trolltech.qt.gui.QAbstractTableModel
`dropMimeData, hasChildren, index, parent`

Methods inherited from class com.trolltech.qt.core.QAbstractItemModel
`beginInsertColumns, beginInsertRows, beginRemoveColumns, beginRemoveRows, buddy, changePersistentIndex, changePersistentIndexList, columnCount, createIndex, createIndex, createIndex, data, data, data, decodeData, encodeData, endInsertColumns, endInsertRows, endRemoveColumns, endRemoveRows, hasChildren, hasIndex, hasIndex, headerData, index, insertColumn, insertColumn, insertColumns, insertRow, insertRow, insertRows, itemData, match, match, match, match, mimeData, mimeTypes, persistentIndexList, removeColumn, removeColumn, removeColumns, removeRow, removeRow, removeRows, reset, rowCount, setData, setData, setData, setHeaderData, setItemData, setSupportedDragActions, setSupportedDragActions, sibling, sort, span, supportedDragActions, supportedDropActions`

Methods inherited from class com.trolltech.qt.core.QObject
`blockSignals, childEvent, children, connectSlotsByName, customEvent, disposeLater, dumpObjectInfo, dumpObjectTree, dynamicPropertyNames, event, eventFilter, findChild, findChild, findChild, findChildren, findChildren, findChildren, findChildren, installEventFilter, isWidgetType, killTimer, moveToThread, objectName, parent, property, removeEventFilter, setObjectName, setParent, setProperty, signalsBlocked, startTimer, thread, timerEvent`

Methods inherited from class com.trolltech.qt.QtJambiObject
`dispose, disposed, finalize, reassignNativeResources, tr, tr, tr`

Methods inherited from class com.trolltech.qt.QSignalEmitter
`disconnect, disconnect, signalSender`

Methods inherited from class java.lang.Object
`clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

Methods inherited from interface com.trolltech.qt.QtJambiInterface
`disableGarbageCollection, nativeId, nativePointer, reenableGarbageCollection, setJavaOwnership`

Field Detail

### beforeDelete

    public final QSignalEmitter.Signal1<java.lang.Integer> beforeDelete

  This signal is emitted before the `row` is deleted.

  Compatible Slot Signatures:
    `void mySlot(int row)`
    `void mySlot()`

### beforeInsert

    public final QSignalEmitter.Signal1<QSqlRecord> beforeInsert

  This signal is emitted before a new row is inserted. The values that are about to be inserted are stored in `record` and can be modified before they will be inserted.

  Compatible Slot Signatures:
    `void mySlot(com.trolltech.qt.sql.QSqlRecord record)`
    `void mySlot()`

### beforeUpdate

    public final QSignalEmitter.Signal2<java.lang.Integer,QSqlRecord> beforeUpdate

  This signal is emitted before the `row` is updated with the values from `record`.

  Note that only values that are marked as generated will be updated. The generated flag can be set with `QSqlRecord::setGenerated` and checked with `QSqlRecord::isGenerated`.

  Compatible Slot Signatures:
    `void mySlot(int row, com.trolltech.qt.sql.QSqlRecord record)`
    `void mySlot(int row)`
    `void mySlot()`
  See Also:
    `QSqlRecord::isGenerated`

### primeInsert

    public final QSignalEmitter.Signal2<java.lang.Integer,QSqlRecord> primeInsert

  This signal is emitted when an insertion is initiated in the given `row`. The `record` parameter can be written to (since it is a reference), for example to populate some fields with default values.

  Compatible Slot Signatures:
    `void mySlot(int row, com.trolltech.qt.sql.QSqlRecord record)`
    `void mySlot(int row)`
    `void mySlot()`

Constructor Detail

### QSqlTableModel

    public QSqlTableModel(QObject parent)

  Equivalent to `QSqlTableModel`(`parent`, QSqlDatabase()).

### QSqlTableModel

    public QSqlTableModel()

  Equivalent to `QSqlTableModel`(0, QSqlDatabase()).

### QSqlTableModel

    public QSqlTableModel(QObject parent,
                          QSqlDatabase db)

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

Method Detail

### database

    public final QSqlDatabase database()

  Returns a pointer to the used `QSqlDatabase` or 0 if no database was set.

### editStrategy

    public final QSqlTableModel.EditStrategy editStrategy()

  Returns the current edit strategy.

  See Also:
    `setEditStrategy`

### fieldIndex

    public final int fieldIndex(java.lang.String fieldName)

  Returns the index of the field `fieldName`.

### filter

    public final java.lang.String filter()

  Returns the currently set filter.

  See Also:
    `setFilter`, `select`

### indexInQuery

    protected final QModelIndex indexInQuery(QModelIndex item)

  Returns the index of the value in the database result set for the given `item` in the model.

  The return value is identical to `item` if no columns or rows have been inserted, removed, or moved around.

  Returns an invalid model index if `item` is out of bounds or if `item` does not point to a value in the result set.

  Overrides:
    `indexInQuery` in class `QSqlQueryModel`
  See Also:
    `QSqlQueryModel::indexInQuery`

### insertRecord

    public final boolean insertRecord(int row,
                                      QSqlRecord record)

  Inserts the `record` after `row`. If `row` is negative, the record will be appended to the end. Calls `insertRows` and `setRecord` internally.

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

  See Also:
    `insertRows`, `removeRows`

### isDirty

    public final boolean isDirty(QModelIndex index)

  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.

### primaryKey

    public final QSqlIndex primaryKey()

  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:
    `setTable`, `setPrimaryKey`, `QSqlDatabase::primaryIndex`

### revertAll

    public final void revertAll()

  Reverts all pending changes.

  See Also:
    `revert`, `revertRow`, `submitAll`

### setPrimaryKey

    protected final void setPrimaryKey(QSqlIndex key)

  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:
    `primaryKey`, `QSqlDatabase::primaryIndex`

### setQuery

    public final void setQuery(QSqlQuery query)

  This function simply calls QSqlQueryModel::setQuery(`query`). You should normally not call it on a `QSqlTableModel`. Instead, use `setTable`, `setSort`, `setFilter`, etc., to set up the query.

  Overrides:
    `setQuery` in class `QSqlQueryModel`
  See Also:
    `selectStatement`

### setRecord

    public final boolean setRecord(int row,
                                   QSqlRecord record)

  Sets the values at the specified `row` to the values of `record`. Returns true if all the values could be set; otherwise returns false.

  See Also:
    `record`

### submitAll

    public final boolean submitAll()

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

  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 again without losing data.

  See Also:
    `revertAll`, `lastError`

### tableName

    public final java.lang.String tableName()

  Returns the name of the currently selected table.

### clear

    public void clear()

  This function is reimplemented for internal reasons.

  Overrides:
    `clear` in class `QSqlQueryModel`

### data

    public java.lang.Object data(QModelIndex idx,
                                 int role)

  This function is reimplemented for internal reasons.

  Overrides:
    `data` in class `QSqlQueryModel`
  See Also:
    `setData`

### deleteRowFromTable

    protected boolean deleteRowFromTable(int row)

  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`

### flags

    public Qt.ItemFlags flags(QModelIndex index)

  This function is reimplemented for internal reasons.

  Overrides:
    `flags` in class `QAbstractItemModel`
  See Also:
    `Qt::ItemFlags`

### headerData

    public java.lang.Object headerData(int section,
                                       Qt.Orientation orientation,
                                       int role)

  This function is reimplemented for internal reasons.

  Overrides:
    `headerData` in class `QSqlQueryModel`
  See Also:
    `setHeaderData`

### insertRowIntoTable

    protected boolean insertRowIntoTable(QSqlRecord values)

  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`

### insertRows

    public boolean insertRows(int row,
                              int count,
                              QModelIndex parent)

  Inserts `count` empty rows at position `row`. Note that `parent` must be invalid, since this model does not support parent-child relations.

  Only one row at a time can be inserted when using the `OnFieldChange` or `OnRowChange` update strategies.

  The `primeInsert` 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.

  Overrides:
    `insertRows` in class `QAbstractItemModel`
  See Also:
    `primeInsert`, `insertRecord`

### orderByClause

    protected java.lang.String orderByClause()

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

  See Also:
    `setSort`, `selectStatement`

### removeColumns

    public boolean removeColumns(int column,
                                 int count,
                                 QModelIndex parent)

  Removes `count` columns from the `parent` model, starting at index `column`.

  Returns if the columns were successfully removed; otherwise returns false.

  Overrides:
    `removeColumns` in class `QSqlQueryModel`
  See Also:
    `removeRows`

### removeRows

    public boolean removeRows(int row,
                              int count,
                              QModelIndex parent)

  Removes `count` rows starting at `row`. Since this model does not support hierarchical structures, `parent` must be an invalid model index.

  Emits the `beforeDelete` signal before a row is deleted.

  Returns true if all rows could be removed; otherwise returns false. Detailed error information can be retrieved using `lastError`.

  Overrides:
    `removeRows` in class `QAbstractItemModel`
  See Also:
    `removeColumns`, `insertRows`

### revert

    public void 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 to `OnRowChange`. Does nothing for the other edit strategies.

  Use `revertAll` to revert all pending changes for the `OnManualSubmit` strategy or `revertRow` to revert a specific row.

  Overrides:
    `revert` in class `QAbstractItemModel`
  See Also:
    `submit`, `submitAll`, `revertRow`, `revertAll`

### revertRow

    public void revertRow(int row)

  Reverts all changes for the specified `row`.

  See Also:
    `revert`, `revertAll`, `submit`, `submitAll`

### rowCount

    public int rowCount(QModelIndex parent)

  This function is reimplemented for internal reasons.

  Overrides:
    `rowCount` in class `QSqlQueryModel`
  See Also:
    `canFetchMore`, `QSqlDriver::hasFeature`

### select

    public boolean select()

  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.

  See Also:
    `setTable`, `setFilter`, `selectStatement`

### selectStatement

    protected java.lang.String selectStatement()

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

  See Also:
    `filter`, `orderByClause`

### setData

    public boolean setData(QModelIndex index,
                           java.lang.Object value,
                           int role)

  Sets the data for the item `index` for the role `role` to `value`. 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 if `index` is out of bounds.

  Overrides:
    `setData` in class `QAbstractItemModel`
  See Also:
    `editStrategy`, `data`, `submit`, `submitAll`, `revertRow`

### setEditStrategy

    public void setEditStrategy(QSqlTableModel.EditStrategy strategy)

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

  This will revert any pending changes.

  See Also:
    `editStrategy`, `revertAll`

### setFilter

    public void setFilter(java.lang.String filter)

  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.

  See Also:
    `filter`, `select`, `selectStatement`, `orderByClause`

### setSort

    public void setSort(int column,
                        Qt.SortOrder order)

  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`

### setTable

    public void setTable(java.lang.String tableName)

  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`

### sort

    public void sort(int column,
                     Qt.SortOrder order)

  Sorts the data by `column` with the sort order `order`. This will immediately select data, use `setSort` to set a sort order without populating the model with data.

  Overrides:
    `sort` in class `QAbstractItemModel`
  See Also:
    `setSort`, `select`, `orderByClause`

### submit

    public boolean 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 to `OnRowChange` or `OnFieldChange`. Does nothing for the `OnManualSubmit` strategy.

  Use `submitAll` to submit all pending changes for the `OnManualSubmit` strategy.

  Returns true on success; otherwise returns false. Use `lastError` to query detailed error information.

  On success the model will be repopulated. Any views presenting it will lose their selections.

  Overrides:
    `submit` in class `QAbstractItemModel`
  See Also:
    `revert`, `revertRow`, `submitAll`, `revertAll`, `lastError`

### updateRowInTable

    protected boolean updateRowInTable(int row,
                                       QSqlRecord values)

  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 QSqlRecord::setGenerated() and tested with QSqlRecord::isGenerated().

  See Also:
    `QSqlRecord::isGenerated`, `setData`

### fromNativePointer

    public static QSqlTableModel fromNativePointer(QNativePointer nativePointer)

  This function returns the QSqlTableModel instance pointed to by nativePointer

  Parameters:
    `nativePointer` - the QNativePointer of which object should be returned.

Overview | Package | Class | Tree | Deprecated | Index | Help
Qt Jambi Home |
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD