Qt:Документация 4.3.2/qsqltablemodel

Материал из Wiki.crossplatform.ru

Версия от 00:51, 12 марта 2010; 91.203.166.22 (Обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск
40px Внимание: Актуальная версия перевода документации находится здесь

__NOTOC__

Image:qt-logo.png

Главная · Все классы · Основные классы · Классы по группам · Модули · Функции

Image:trolltech-logo.png

Содержание

[править] Описание класса QSqlTableModel
[модуль QtSql ]

Класс QSqlTableModel предоставляет редактируемую модель данных для одной таблицы базы данных. Подробнее...

 #include <QSqlTableModel>

Наследует QSqlQueryModel.

Наследуется QSqlRelationalTableModel.

[править] Открытые типы

  • 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 )
  • virtual bool insertRows ( int row, int count, const QModelIndex & parent = QModelIndex() )
  • bool isDirty ( const QModelIndex & index ) const
  • QSqlIndex primaryKey () const
  • virtual bool removeColumns ( int column, int count, const QModelIndex & parent = QModelIndex() )
  • virtual bool removeRows ( int row, int count, const QModelIndex & parent = QModelIndex() )
  • virtual void revertRow ( int row )
  • virtual bool select ()
  • virtual bool setData ( const QModelIndex & index, const QVariant & value, int role = Qt::EditRole )
  • 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 )
  • virtual void sort ( int column, Qt::SortOrder order )
  • QString tableName () const
  • 15 открытых функций унаследованных от QSqlQueryModel
  • 1 открытая функция унаследованная от QAbstractTableModel
  • 34 открытых функций унаследованных от QAbstractItemModel
  • 29 открытых функций унаследованных от QObject

[править] Открытые слоты

  • 2 открытых слотов унаследованных от QAbstractItemModel
  • 1 открытый слот унаследованный от QObject

[править] Сигналы

[править] Защищенные функции

  • 3 защищенных функций унаследованных от QSqlQueryModel
  • 14 защищенных функций унаследованных от QAbstractItemModel
  • 7 защищенных функций унаследованных от QObject

[править] Дополнительные унаследованные члены

  • 1 свойство унаследованное от QObject
  • 5 статических открытых члена унаследованных от QObject

[править] Подробное описание

Класс QSqlTableModel предоставляет редактируемую модель данных для одной таблицы базы данных.

QSqlTableModel это высокоуровневый интерфейс к записям одной таблицы базы данных с возможностью и чтения и записи. Он является надстройкой нижнего уровня QSqlQuery и может быть использован, чтобы предоставлять данные для классов представлений таких как QTableView. Например:

     QSqlTableModel *model = new QSqlTableModel;
     model->setTable("employee");
     model->setEditStrategy(QSqlTableModel::OnManualSubmit);
     model->select();
     model->removeColumn(0); // прячем поле ID
     model->setHeaderData(0, Qt::Horizontal, tr("Name"));
     model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
 
     QTableView *view = new QTableView;
     view->setModel(model);
     view->show();

Мы устанавливаем имя SQL таблицы и стратегию редактирования, затем мы устанавливаем метки отображаемые в заголовках представления. Стратегия редактирования предписывает, когда изменения сделаные пользователем в представлении применяются в базе данных. Возможные значения стратегии, это OnFieldChange, OnRowChange, и OnManualSubmit.

QSqlTableModel может быть также использован для доступа к базе данных программно, без связывания ее с представлением:

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

Фрагмент кода выше извлекает поле salary из 4 записи выбранной по запросу SELECT * FROM employee.

Имеется возможность установить фильтры используя setFilter(), или изменить порядок сортировки используя setSort(). В конце, вы должны вызвать select(), чтобы заполнить модель данными.

Пример sql/tablemodel илюстрирует, как использовать QSqlTableModel в качестве источника данных для QTableView.

QSqlTableModel не предоставляет непосредственную поддержку внешних ключей. Если вы хотите разрешить внешние ключи используйте QSqlRelationalTableModel и QSqlRelationalDelegate.

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, Table Model Example, and Cached Table Example.


[править] Описание типов членов

[править]
enum QSqlTableModel::EditStrategy

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

See also setEditStrategy().


[править] Описание функций-членов

[править]
QSqlTableModel::QSqlTableModel ( QObject * parent = 0, QSqlDatabase db = QSqlDatabase() )

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.

[править]
QSqlTableModel::~QSqlTableModel () [virtual]

Destroys the object and frees any allocated resources.

[править]
void QSqlTableModel::beforeDelete ( int row ) [signal]

This signal is emitted before the row is deleted.

[править]
void QSqlTableModel::beforeInsert ( QSqlRecord & record ) [signal]

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.

[править]
void QSqlTableModel::beforeUpdate ( int row, QSqlRecord & record ) [signal]

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

See also QSqlRecord::isGenerated().

[править]
QSqlDatabase QSqlTableModel::database () const

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

[править]
bool QSqlTableModel::deleteRowFromTable ( int row ) [virtual protected]

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() and removeRows().

[править]
EditStrategy QSqlTableModel::editStrategy () const

Returns the current edit strategy.

See also setEditStrategy().

[править]
int QSqlTableModel::fieldIndex ( const QString & fieldName ) const

Returns the index of the field fieldName.

[править]
QString QSqlTableModel::filter () const

Returns the currently set filter.

See also setFilter() and select().

[править]
QModelIndex QSqlTableModel::indexInQuery ( const QModelIndex & item ) const [protected]

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.

See also QSqlQueryModel::indexInQuery().

[править]
bool QSqlTableModel::insertRecord ( int row, const 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() and removeRows().

[править]
bool QSqlTableModel::insertRowIntoTable ( const QSqlRecord & values ) [virtual protected]

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(), and insertRows().

[править]
bool QSqlTableModel::insertRows ( int row, int count, const QModelIndex & parent = QModelIndex() ) [virtual]

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.

Reimplemented from QAbstractItemModel.

See also primeInsert() and insertRecord().

[править]
bool QSqlTableModel::isDirty ( const QModelIndex & index ) const

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.

[править]
QString QSqlTableModel::orderByClause () const [virtual protected]

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

See also setSort() and selectStatement().

[править]
QSqlIndex QSqlTableModel::primaryKey () const

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(), and QSqlDatabase::primaryIndex().

[править]
void QSqlTableModel::primeInsert ( int row, QSqlRecord & record ) [signal]

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.

[править]
bool QSqlTableModel::removeColumns ( int column, int count, const QModelIndex & parent = QModelIndex() ) [virtual]

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

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

Reimplemented from QAbstractItemModel.

See also removeRows().

[править]
bool QSqlTableModel::removeRows ( int row, int count, const QModelIndex & parent = QModelIndex() ) [virtual]

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

Reimplemented from QAbstractItemModel.

See also removeColumns() and insertRows().

[править]
void QSqlTableModel::revert () [virtual slot]

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.

Reimplemented from QAbstractItemModel.

See also submit(), submitAll(), revertRow(), and revertAll().

[править]
void QSqlTableModel::revertAll () [slot]

Reverts all pending changes.

See also revert(), revertRow(), and submitAll().

[править]
void QSqlTableModel::revertRow ( int row ) [virtual]

Reverts all changes for the specified row.

See also revert(), revertAll(), submit(), and submitAll().

[править]
bool QSqlTableModel::select () [virtual]

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(), and selectStatement().

[править]
QString QSqlTableModel::selectStatement () const [virtual protected]

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

See also filter() and orderByClause().

[править]
bool QSqlTableModel::setData ( const QModelIndex & index, const QVariant & value, int role = Qt::EditRole ) [virtual]

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.

Reimplemented from QAbstractItemModel.

See also editStrategy(), data(), submit(), submitAll(), and revertRow().

[править]
void QSqlTableModel::setEditStrategy ( EditStrategy strategy ) [virtual]

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

This will revert any pending changes.

See also editStrategy() and revertAll().

[править]
void QSqlTableModel::setFilter ( const QString & filter ) [virtual]

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(), and orderByClause().

[править]
void QSqlTableModel::setPrimaryKey ( const QSqlIndex & key ) [protected]

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() and QSqlDatabase::primaryIndex().

[править]
void QSqlTableModel::setQuery ( const QSqlQuery & query ) [protected]

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.

See also selectStatement().

[править]
bool QSqlTableModel::setRecord ( int row, const 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().

[править]
void QSqlTableModel::setSort ( int column, Qt::SortOrder order ) [virtual]

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(), and orderByClause().

[править]
void QSqlTableModel::setTable ( const QString & tableName ) [virtual]

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(), and lastError().

[править]
void QSqlTableModel::sort ( int column, Qt::SortOrder order ) [virtual]

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.

Reimplemented from QAbstractItemModel.

See also setSort(), select(), and orderByClause().

[править]
bool QSqlTableModel::submit () [virtual slot]

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.

Reimplemented from QAbstractItemModel.

See also revert(), revertRow(), submitAll(), revertAll(), and lastError().

[править]
bool QSqlTableModel::submitAll () [slot]

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() and lastError().

[править]
QString QSqlTableModel::tableName () const

Returns the name of the currently selected table.

[править]
bool QSqlTableModel::updateRowInTable ( int row, const QSqlRecord & values ) [virtual protected]

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() and setData().


Copyright © 2007 Trolltech Trademarks
Qt 4.3.2