The QSqlTableModel class provides an editable data model for a single database table. 更多...
| 头: | #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 ) |
| bool | isDirty (const QModelIndex & index ) const |
| QSqlIndex | primaryKey () const |
| virtual void | revertRow (int row ) |
| virtual bool | select () |
| 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 ) |
| QString | tableName () const |
| virtual void | clear () |
| virtual QVariant | data (const QModelIndex & index , int role = Qt::DisplayRole) const |
| virtual Qt::ItemFlags | flags (const QModelIndex & index ) const |
| virtual QVariant | headerData (int section , Qt::Orientation orientation , int role = Qt::DisplayRole) const |
| virtual bool | insertRows (int row , int count , const QModelIndex & parent = QModelIndex()) |
| virtual bool | removeColumns (int column , int count , const QModelIndex & parent = QModelIndex()) |
| virtual bool | removeRows (int row , int count , const QModelIndex & parent = QModelIndex()) |
| virtual int | rowCount (const QModelIndex & parent = QModelIndex()) const |
| virtual bool | setData (const QModelIndex & index , const QVariant & value , int role = Qt::EditRole) |
| virtual void | sort (int column , Qt::SortOrder order ) |
| virtual void | revert () |
| void | revertAll () |
| virtual bool | submit () |
| bool | submitAll () |
| void | beforeDelete (int row ) |
| void | beforeInsert (QSqlRecord & record ) |
| void | beforeUpdate (int row , QSqlRecord & record ) |
| void | primeInsert (int row , QSqlRecord & record ) |
| virtual bool | deleteRowFromTable (int row ) |
| QModelIndex | indexInQuery (const QModelIndex & item ) const |
| virtual bool | insertRowIntoTable (const QSqlRecord & 值 ) |
| virtual QString | orderByClause () const |
| virtual QString | selectStatement () const |
| void | setPrimaryKey (const QSqlIndex & key ) |
| void | setQuery (const QSqlQuery & query ) |
| virtual bool | updateRowInTable (int row , const QSqlRecord & 值 ) |
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 。例如:
QSqlTableModel *model = new QSqlTableModel(parentObject, database);
model->setTable("employee");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
QTableView *view = new 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 ,和 OnManualSubmit .
QSqlTableModel can also be used to access a database programmatically, without binding it to a view:
QSqlQueryModel model;
model.setQuery("SELECT * FROM employee");
int 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 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.
另请参阅 QSqlRelationalTableModel , QSqlQuery , 模型/视图编程 , 表格模型范例 ,和 Cached Table Example .
This enum type describes which strategy to choose when editing values in the database.
| 常量 | 值 | 描述 |
|---|---|---|
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 () 或 revertAll () 被调用。 |
Note: To prevent inserting only partly initialized rows into the database,
OnFieldChange
will behave like
OnRowChange
for newly inserted rows.
另请参阅 setEditStrategy ().
创建空 QSqlTableModel and sets the parent to parent and the database connection to db 。若 db is not valid, the default database connection will be used.
The default edit strategy is OnRowChange .
[虚拟]
QSqlTableModel::
~QSqlTableModel
()
销毁对象并释放任何分配资源。
[signal]
void
QSqlTableModel::
beforeDelete
(
int
row
)
此信号被发射由 deleteRowFromTable () before the row is deleted from the currently active database table.
[signal]
void
QSqlTableModel::
beforeInsert
(
QSqlRecord
&
record
)
此信号被发射由 insertRowIntoTable () before a new row is inserted into the currently active database table. The values that are about to be inserted are stored in record and can be modified before they will be inserted.
[signal]
void
QSqlTableModel::
beforeUpdate
(
int
row
,
QSqlRecord
&
record
)
此信号被发射由 updateRowInTable () before the row is 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 QSqlRecord::setGenerated () and checked with QSqlRecord::isGenerated ().
另请参阅 QSqlRecord::isGenerated ().
[虚拟]
void
QSqlTableModel::
clear
()
重实现自 QSqlQueryModel::clear ().
[虚拟]
QVariant
QSqlTableModel::
data
(const
QModelIndex
&
index
,
int
role
= Qt::DisplayRole) const
重实现自 QAbstractItemModel::data ().
另请参阅 setData ().
Returns a pointer to the used QSqlDatabase or 0 if no database was set.
[virtual protected]
bool
QSqlTableModel::
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 () 或 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.
另请参阅 removeRow () 和 removeRows ().
Returns the current edit strategy.
另请参阅 setEditStrategy ().
Returns the index of the field fieldName , or -1 if no corresponding field exists in the model.
Returns the currently set filter.
另请参阅 setFilter () 和 select ().
[虚拟]
Qt::ItemFlags
QSqlTableModel::
flags
(const
QModelIndex
&
index
) const
重实现自 QAbstractItemModel::flags ().
[虚拟]
QVariant
QSqlTableModel::
headerData
(
int
section
,
Qt::Orientation
orientation
,
int
role
= Qt::DisplayRole) const
重实现自 QAbstractItemModel::headerData ().
[protected]
QModelIndex
QSqlTableModel::
indexInQuery
(const
QModelIndex
&
item
) const
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.
另请参阅 QSqlQueryModel::indexInQuery ().
插入 record after row 。若 row is negative, the record will be appended to the end. Calls insertRows () 和 setRecord () internally.
Returns true if the row could be inserted, otherwise false.
另请参阅 insertRows () 和 removeRows ().
[virtual protected]
bool
QSqlTableModel::
insertRowIntoTable
(const
QSqlRecord
&
值
)
Inserts the 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 () 和 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 ().
另请参阅 lastError (), insertRow (),和 insertRows ().
[虚拟]
bool
QSqlTableModel::
insertRows
(
int
row
,
int
count
, const
QModelIndex
&
parent
= QModelIndex())
重实现自 QAbstractItemModel::insertRows ().
插入 count empty rows at position row 。注意, 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.
另请参阅 primeInsert () 和 insertRecord ().
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.
若 index is invalid or points to a non-existing row, false is returned.
[virtual protected]
QString
QSqlTableModel::
orderByClause
() const
Returns an SQL
ORDER BY
clause based on the currently set sort order.
另请参阅 setSort () 和 selectStatement ().
Returns the primary key for the current table, or an empty QSqlIndex if the table is not set or has no primary key.
另请参阅 setTable (), setPrimaryKey (),和 QSqlDatabase::primaryIndex ().
[signal]
void
QSqlTableModel::
primeInsert
(
int
row
,
QSqlRecord
&
record
)
此信号被发射由 insertRows (), when an insertion is initiated in the given row of the currently active database table. 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())
重实现自 QAbstractItemModel::removeColumns ().
移除 count columns from the parent model, starting at index column .
Returns if the columns were successfully removed; otherwise returns false.
另请参阅 removeRows ().
[虚拟]
bool
QSqlTableModel::
removeRows
(
int
row
,
int
count
, const
QModelIndex
&
parent
= QModelIndex())
重实现自 QAbstractItemModel::removeRows ().
移除 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. When the edit strategy is OnManualSubmit signal emission is delayed until submitAll () 被调用。
Returns true if all rows could be removed; otherwise returns false. Detailed error information can be retrieved using lastError ().
另请参阅 removeColumns () 和 insertRows ().
[virtual slot]
void
QSqlTableModel::
revert
()
重实现自 QAbstractItemModel::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.
使用 revertAll () to revert all pending changes for the OnManualSubmit strategy or revertRow () to revert a specific row.
另请参阅 submit (), submitAll (), revertRow (),和 revertAll ().
[slot]
void
QSqlTableModel::
revertAll
()
Reverts all pending changes.
另请参阅 revert (), revertRow (),和 submitAll ().
[虚拟]
void
QSqlTableModel::
revertRow
(
int
row
)
Reverts all changes for the specified row .
另请参阅 revert (), revertAll (), submit (),和 submitAll ().
[虚拟]
int
QSqlTableModel::
rowCount
(const
QModelIndex
&
parent
= QModelIndex()) const
重实现自 QAbstractItemModel::rowCount ().
[虚拟]
bool
QSqlTableModel::
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.
注意: Calling select() will revert any unsubmitted changes and remove any inserted columns.
另请参阅 setTable (), setFilter (),和 selectStatement ().
[virtual protected]
QString
QSqlTableModel::
selectStatement
() const
Returns the SQL
SELECT
statement used internally to populate the model. The statement includes the filter and the
ORDER BY
子句。
另请参阅 filter () 和 orderByClause ().
[虚拟]
bool
QSqlTableModel::
setData
(const
QModelIndex
&
index
, const
QVariant
&
value
,
int
role
= Qt::EditRole)
重实现自 QAbstractItemModel::setData ().
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.
另请参阅 editStrategy (), data (), submit (), submitAll (),和 revertRow ().
[虚拟]
void
QSqlTableModel::
setEditStrategy
(
EditStrategy
strategy
)
Sets the strategy for editing values in the database to strategy .
This will revert any pending changes.
另请参阅 editStrategy () 和 revertAll ().
[虚拟]
void
QSqlTableModel::
setFilter
(const
QString
&
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 () 被调用。
另请参阅 filter (), select (), selectStatement (),和 orderByClause ().
[protected]
void
QSqlTableModel::
setPrimaryKey
(const
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 ().
另请参阅 primaryKey () 和 QSqlDatabase::primaryIndex ().
[protected]
void
QSqlTableModel::
setQuery
(const
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.
另请参阅 selectStatement ().
Sets the values at the specified row to the values of record . Returns true if all the values could be set; otherwise returns false.
另请参阅 record ().
[虚拟]
void
QSqlTableModel::
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 ().
另请参阅 sort (), select (),和 orderByClause ().
[虚拟]
void
QSqlTableModel::
setTable
(const
QString
&
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 ().
另请参阅 select (), setFilter (),和 lastError ().
[虚拟]
void
QSqlTableModel::
sort
(
int
column
,
Qt::SortOrder
order
)
重实现自 QAbstractItemModel::sort ().
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.
另请参阅 setSort (), select (),和 orderByClause ().
[virtual slot]
bool
QSqlTableModel::
submit
()
重实现自 QAbstractItemModel::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.
使用 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.
另请参阅 revert (), revertRow (), submitAll (), revertAll (),和 lastError ().
[slot]
bool
QSqlTableModel::
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.
另请参阅 revertAll () 和 lastError ().
Returns the name of the currently selected table.
[virtual protected]
bool
QSqlTableModel::
updateRowInTable
(
int
row
, const
QSqlRecord
&
值
)
Updates the given row in the currently active database table with the specified 值 . 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 ().
另请参阅 QSqlRecord::isGenerated () 和 setData ().