Qt 4.8
Public Types | Public Slots | Signals | Public Functions | Protected Functions | List of all members
QSqlTableModel Class Reference

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

#include <qsqltablemodel.h>

Inheritance diagram for QSqlTableModel:
QSqlQueryModel QAbstractTableModel QAbstractItemModel QObject QRelatedTableModel QSqlRelationalTableModel

Public Types

enum  EditStrategy { OnFieldChange, OnRowChange, OnManualSubmit }
 This enum type describes which strategy to choose when editing values in the database. More...
 

Public Slots

void revert ()
 This reimplemented slot is called by the item delegates when the user canceled editing the current row. More...
 
void revertAll ()
 Reverts all pending changes. More...
 
bool submit ()
 This reimplemented slot is called by the item delegates when the user stopped editing the current row. More...
 
bool submitAll ()
 Submits all pending changes and returns true on success. More...
 
- Public Slots inherited from QAbstractItemModel
virtual void revert ()
 Lets the model know that it should discard cached information. More...
 
virtual bool submit ()
 Lets the model know that it should submit cached information to permanent storage. More...
 
- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 

Signals

void beforeDelete (int row)
 This signal is emitted by deleteRowFromTable() before the row is deleted from the currently active database table. More...
 
void beforeInsert (QSqlRecord &record)
 This signal is emitted by insertRowIntoTable() before a new row is inserted into the currently active database table. More...
 
void beforeUpdate (int row, QSqlRecord &record)
 This signal is emitted by updateRowInTable() before the row is updated in the currently active database table with the values from record. More...
 
void primeInsert (int row, QSqlRecord &record)
 This signal is emitted by insertRows(), when an insertion is initiated in the given row of the currently active database table. More...
 
- Signals inherited from QAbstractItemModel
void columnsAboutToBeInserted (const QModelIndex &parent, int first, int last)
 This signal is emitted just before columns are inserted into the model. More...
 
void columnsAboutToBeMoved (const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationColumn)
 This signal is emitted just before columns are moved within the model. More...
 
void columnsAboutToBeRemoved (const QModelIndex &parent, int first, int last)
 This signal is emitted just before columns are removed from the model. More...
 
void columnsInserted (const QModelIndex &parent, int first, int last)
 This signal is emitted after columns have been inserted into the model. More...
 
void columnsMoved (const QModelIndex &parent, int start, int end, const QModelIndex &destination, int column)
 This signal is emitted after columns have been moved within the model. More...
 
void columnsRemoved (const QModelIndex &parent, int first, int last)
 This signal is emitted after columns have been removed from the model. More...
 
void dataChanged (const QModelIndex &topLeft, const QModelIndex &bottomRight)
 This signal is emitted whenever the data in an existing item changes. More...
 
void headerDataChanged (Qt::Orientation orientation, int first, int last)
 This signal is emitted whenever a header is changed. More...
 
void layoutAboutToBeChanged ()
 This signal is emitted just before the layout of a model is changed. More...
 
void layoutChanged ()
 This signal is emitted whenever the layout of items exposed by the model has changed; for example, when the model has been sorted. More...
 
void modelAboutToBeReset ()
 This signal is emitted when reset() is called, before the model's internal state (e. More...
 
void modelReset ()
 This signal is emitted when reset() is called, after the model's internal state (e. More...
 
void rowsAboutToBeInserted (const QModelIndex &parent, int first, int last)
 This signal is emitted just before rows are inserted into the model. More...
 
void rowsAboutToBeMoved (const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)
 This signal is emitted just before rows are moved within the model. More...
 
void rowsAboutToBeRemoved (const QModelIndex &parent, int first, int last)
 This signal is emitted just before rows are removed from the model. More...
 
void rowsInserted (const QModelIndex &parent, int first, int last)
 This signal is emitted after rows have been inserted into the model. More...
 
void rowsMoved (const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row)
 This signal is emitted after rows have been moved within the model. More...
 
void rowsRemoved (const QModelIndex &parent, int first, int last)
 This signal is emitted after rows have been removed from the model. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 

Public Functions

void clear ()
 Reimplemented Function More...
 
QVariant data (const QModelIndex &idx, int role=Qt::DisplayRole) const
 Reimplemented Function More...
 
QSqlDatabase database () const
 Returns a pointer to the used QSqlDatabase or 0 if no database was set. More...
 
EditStrategy editStrategy () const
 Returns the current edit strategy. More...
 
int fieldIndex (const QString &fieldName) const
 Returns the index of the field fieldName, or -1 if no corresponding field exists in the model. More...
 
QString filter () const
 Returns the currently set filter. More...
 
Qt::ItemFlags flags (const QModelIndex &index) const
 Reimplemented Function More...
 
QVariant headerData (int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const
 Reimplemented Function More...
 
bool insertRecord (int row, const QSqlRecord &record)
 Inserts the record after row. More...
 
bool insertRows (int row, int count, const QModelIndex &parent=QModelIndex())
 Inserts count empty rows at position row. More...
 
bool isDirty (const QModelIndex &index) const
 Returns true if the value at the index index is dirty, otherwise false. More...
 
QSqlIndex 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. More...
 
 QSqlTableModel (QObject *parent=0, QSqlDatabase db=QSqlDatabase())
 Creates an empty QSqlTableModel and sets the parent to parent and the database connection to db. More...
 
bool removeColumns (int column, int count, const QModelIndex &parent=QModelIndex())
 Removes count columns from the parent model, starting at index column. More...
 
bool removeRows (int row, int count, const QModelIndex &parent=QModelIndex())
 Removes count rows starting at row. More...
 
virtual void revertRow (int row)
 Reverts all changes for the specified row. More...
 
int rowCount (const QModelIndex &parent=QModelIndex()) const
 Reimplemented Function More...
 
virtual bool 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. More...
 
bool setData (const QModelIndex &index, const QVariant &value, int role=Qt::EditRole)
 Sets the data for the item index for the role role to value. More...
 
virtual void setEditStrategy (EditStrategy strategy)
 Sets the strategy for editing values in the database to strategy. More...
 
virtual void setFilter (const QString &filter)
 Sets the current filter to filter. More...
 
bool setRecord (int row, const QSqlRecord &record)
 Sets the values at the specified row to the values of record. More...
 
virtual void setSort (int column, Qt::SortOrder order)
 Sets the sort order for column to order. More...
 
virtual void setTable (const QString &tableName)
 Sets the database table on which the model operates to tableName. More...
 
void sort (int column, Qt::SortOrder order)
 Sorts the data by column with the sort order order. More...
 
QString tableName () const
 Returns the name of the currently selected table. More...
 
virtual ~QSqlTableModel ()
 Destroys the object and frees any allocated resources. More...
 
- Public Functions inherited from QSqlQueryModel
bool canFetchMore (const QModelIndex &parent=QModelIndex()) const
 Returns true if it is possible to read more rows from the database. More...
 
int columnCount (const QModelIndex &parent=QModelIndex()) const
 Reimplemented Function More...
 
void fetchMore (const QModelIndex &parent=QModelIndex())
 Fetches more rows from a database. More...
 
bool insertColumns (int column, int count, const QModelIndex &parent=QModelIndex())
 Inserts count columns into the model at position column. More...
 
QSqlError lastError () const
 Returns information about the last error that occurred on the database. More...
 
 QSqlQueryModel (QObject *parent=0)
 Creates an empty QSqlQueryModel with the given parent. More...
 
QSqlQuery query () const
 Returns the QSqlQuery associated with this model. More...
 
QSqlRecord record (int row) const
 Returns the record containing information about the fields of the current query. More...
 
QSqlRecord record () const
 Returns an empty record containing information about the fields of the current query. More...
 
bool setHeaderData (int section, Qt::Orientation orientation, const QVariant &value, int role=Qt::EditRole)
 Sets the caption for a horizontal header for the specified role to value. More...
 
void setQuery (const QSqlQuery &query)
 Resets the model and sets the data provider to be the given query. More...
 
void setQuery (const QString &query, const QSqlDatabase &db=QSqlDatabase())
 Executes the query query for the given database connection db. More...
 
virtual ~QSqlQueryModel ()
 Destroys the object and frees any allocated resources. More...
 
- Public Functions inherited from QAbstractTableModel
bool dropMimeData (const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
 Reimplemented Function More...
 
QModelIndex index (int row, int column, const QModelIndex &parent=QModelIndex()) const
 Returns the index of the data in row and column with parent. More...
 
 QAbstractTableModel (QObject *parent=0)
 Constructs an abstract table model for the given parent. More...
 
 ~QAbstractTableModel ()
 Destroys the abstract table model. More...
 
- Public Functions inherited from QAbstractItemModel
virtual QModelIndex buddy (const QModelIndex &index) const
 Returns a model index for the buddy of the item represented by index. More...
 
bool hasIndex (int row, int column, const QModelIndex &parent=QModelIndex()) const
 Returns true if the model returns a valid QModelIndex for row and column with parent, otherwise returns false. More...
 
bool insertColumn (int column, const QModelIndex &parent=QModelIndex())
 Inserts a single column before the given column in the child items of the parent specified. More...
 
bool insertRow (int row, const QModelIndex &parent=QModelIndex())
 Inserts a single row before the given row in the child items of the parent specified. More...
 
virtual QMap< int, QVariantitemData (const QModelIndex &index) const
 Returns a map with values for all predefined roles in the model for the item at the given index. More...
 
virtual QModelIndexList match (const QModelIndex &start, int role, const QVariant &value, int hits=1, Qt::MatchFlags flags=Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const
 Returns a list of indexes for the items in the column of the start index where data stored under the given role matches the specified value. More...
 
virtual QMimeDatamimeData (const QModelIndexList &indexes) const
 Returns an object that contains serialized items of data corresponding to the list of indexes specified. More...
 
virtual QStringList mimeTypes () const
 Returns a list of MIME types that can be used to describe a list of model indexes. More...
 
 QAbstractItemModel (QObject *parent=0)
 Constructs an abstract item model with the given parent. More...
 
bool removeColumn (int column, const QModelIndex &parent=QModelIndex())
 Removes the given column from the child items of the parent specified. More...
 
bool removeRow (int row, const QModelIndex &parent=QModelIndex())
 Removes the given row from the child items of the parent specified. More...
 
const QHash< int, QByteArray > & roleNames () const
 Returns the model's role names. More...
 
virtual bool setItemData (const QModelIndex &index, const QMap< int, QVariant > &roles)
 Sets the role data for the item at index to the associated value in roles, for every Qt::ItemDataRole. More...
 
void setSupportedDragActions (Qt::DropActions)
 Sets the supported drag actions for the items in the model. More...
 
QModelIndex sibling (int row, int column, const QModelIndex &idx) const
 Returns the sibling at row and column for the item at index, or an invalid QModelIndex if there is no sibling at that location. More...
 
virtual QSize span (const QModelIndex &index) const
 Returns the row and column span of the item represented by index. More...
 
Qt::DropActions supportedDragActions () const
 Returns the actions supported by the data in this model. More...
 
virtual Qt::DropActions supportedDropActions () const
 Returns the drop actions supported by this model. More...
 
virtual ~QAbstractItemModel ()
 Destroys the abstract item model. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Protected Functions

virtual bool deleteRowFromTable (int row)
 Deletes the given row from the currently active database table. More...
 
QModelIndex indexInQuery (const QModelIndex &item) const
 Returns the index of the value in the database result set for the given item in the model. More...
 
virtual bool insertRowIntoTable (const QSqlRecord &values)
 Inserts the values values into the currently active database table. More...
 
virtual QString orderByClause () const
 Returns an SQL ORDER BY clause based on the currently set sort order. More...
 
 QSqlTableModel (QSqlTableModelPrivate &dd, QObject *parent=0, QSqlDatabase db=QSqlDatabase())
 
virtual QString selectStatement () const
 Returns the SQL SELECT statement used internally to populate the model. More...
 
void setPrimaryKey (const QSqlIndex &key)
 Protected method that allows subclasses to set the primary key to key. More...
 
void setQuery (const QSqlQuery &query)
 This function simply calls QSqlQueryModel::setQuery(query). More...
 
virtual bool updateRowInTable (int row, const QSqlRecord &values)
 Updates the given row in the currently active database table with the specified values. More...
 
- Protected Functions inherited from QSqlQueryModel
QModelIndex indexInQuery (const QModelIndex &item) const
 Returns the index of the value in the database result set for the given item in the model. More...
 
 QSqlQueryModel (QSqlQueryModelPrivate &dd, QObject *parent=0)
 
virtual void queryChange ()
 This virtual function is called whenever the query changes. More...
 
void setLastError (const QSqlError &error)
 Protected function which allows derived classes to set the value of the last error that occurred on the database to error. More...
 
- Protected Functions inherited from QAbstractTableModel
 QAbstractTableModel (QAbstractItemModelPrivate &dd, QObject *parent)
 Constructs an abstract table model with dd and the given parent. More...
 
- Protected Functions inherited from QAbstractItemModel
void beginInsertColumns (const QModelIndex &parent, int first, int last)
 Begins a column insertion operation. More...
 
void beginInsertRows (const QModelIndex &parent, int first, int last)
 Begins a row insertion operation. More...
 
bool beginMoveColumns (const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationColumn)
 Begins a column move operation. More...
 
bool beginMoveRows (const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationRow)
 Begins a row move operation. More...
 
void beginRemoveColumns (const QModelIndex &parent, int first, int last)
 Begins a column removal operation. More...
 
void beginRemoveRows (const QModelIndex &parent, int first, int last)
 Begins a row removal operation. More...
 
void beginResetModel ()
 Begins a model reset operation. More...
 
void changePersistentIndex (const QModelIndex &from, const QModelIndex &to)
 Changes the QPersistentModelIndex that is equal to the given from model index to the given to model index. More...
 
void changePersistentIndexList (const QModelIndexList &from, const QModelIndexList &to)
 Changes the QPersistentModelIndexes that is equal to the indexes in the given from model index list to the given to model index list. More...
 
QModelIndex createIndex (int row, int column, void *data=0) const
 Creates a model index for the given row and column with the internal pointer ptr. More...
 
QModelIndex createIndex (int row, int column, int id) const
 Use QModelIndex QAbstractItemModel::createIndex(int row, int column, quint32 id) instead. More...
 
QModelIndex createIndex (int row, int column, quint32 id) const
 Creates a model index for the given row and column with the internal identifier, id. More...
 
bool decodeData (int row, int column, const QModelIndex &parent, QDataStream &stream)
 
void encodeData (const QModelIndexList &indexes, QDataStream &stream) const
 
void endInsertColumns ()
 Ends a column insertion operation. More...
 
void endInsertRows ()
 Ends a row insertion operation. More...
 
void endMoveColumns ()
 Ends a column move operation. More...
 
void endMoveRows ()
 Ends a row move operation. More...
 
void endRemoveColumns ()
 Ends a column removal operation. More...
 
void endRemoveRows ()
 Ends a row removal operation. More...
 
void endResetModel ()
 Completes a model reset operation. More...
 
QModelIndexList persistentIndexList () const
 Returns the list of indexes stored as persistent indexes in the model. More...
 
 QAbstractItemModel (QAbstractItemModelPrivate &dd, QObject *parent=0)
 
void reset ()
 Resets the model to its original state in any attached views. More...
 
void setRoleNames (const QHash< int, QByteArray > &roleNames)
 Sets the model's role names to roleNames. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Additional Inherited Members

- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Slots inherited from QAbstractItemModel
void resetInternalData ()
 This slot is called just after the internal data of a model is cleared while it is being reset. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

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

Attention
Module: QtSql

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(parentObject, database);
model->setTable("employee");
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 , and OnManualSubmit .

QSqlTableModel can also be used to access a database programmatically, without binding it to a view:

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.

See also
QSqlRelationalTableModel, QSqlQuery, {Model/View Programming}, {Table Model Example}, {Cached Table Example}

Definition at line 59 of file qsqltablemodel.h.

Enumerations

◆ EditStrategy

This enum type describes which strategy to choose when editing values in the database.

  • OnFieldChange All changes to the model will be applied immediately to the database.
  • OnRowChange Changes to a row will be applied when the user selects a different row.
  • 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.

See also
setEditStrategy()
Enumerator
OnFieldChange 
OnRowChange 
OnManualSubmit 

Definition at line 65 of file qsqltablemodel.h.

Constructors and Destructors

◆ QSqlTableModel() [1/2]

QSqlTableModel::QSqlTableModel ( QObject parent = 0,
QSqlDatabase  db = QSqlDatabase() 
)
explicit

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 .

Definition at line 370 of file qsqltablemodel.cpp.

371  : QSqlQueryModel(*new QSqlTableModelPrivate, parent)
372 {
374  d->db = db.isValid() ? db : QSqlDatabase::database();
375 }
double d
Definition: qnumeric_p.h:62
bool isValid() const
Returns true if the QSqlDatabase has a valid driver.
#define Q_D(Class)
Definition: qglobal.h:2482
static QSqlDatabase database(const QString &connectionName=QLatin1String(defaultConnection), bool open=true)
Returns the database connection called connectionName.
The QSqlTableModel class provides an editable data model for a single database table.
QSqlQueryModel(QObject *parent=0)
Creates an empty QSqlQueryModel with the given parent.

◆ ~QSqlTableModel()

QSqlTableModel::~QSqlTableModel ( )
virtual

Destroys the object and frees any allocated resources.

Definition at line 389 of file qsqltablemodel.cpp.

390 {
391 }

◆ QSqlTableModel() [2/2]

QSqlTableModel::QSqlTableModel ( QSqlTableModelPrivate dd,
QObject parent = 0,
QSqlDatabase  db = QSqlDatabase() 
)
protected
Warning
This function is not part of the public interface.

Definition at line 379 of file qsqltablemodel.cpp.

380  : QSqlQueryModel(dd, parent)
381 {
383  d->db = db.isValid() ? db : QSqlDatabase::database();
384 }
double d
Definition: qnumeric_p.h:62
bool isValid() const
Returns true if the QSqlDatabase has a valid driver.
#define Q_D(Class)
Definition: qglobal.h:2482
static QSqlDatabase database(const QString &connectionName=QLatin1String(defaultConnection), bool open=true)
Returns the database connection called connectionName.
The QSqlTableModel class provides an editable data model for a single database table.
QSqlQueryModel(QObject *parent=0)
Creates an empty QSqlQueryModel with the given parent.

Functions

◆ beforeDelete

QSqlTableModel::beforeDelete ( int  row)
signal

This signal is emitted by deleteRowFromTable() before the row is deleted from the currently active database table.

Referenced by deleteRowFromTable().

◆ beforeInsert

QSqlTableModel::beforeInsert ( QSqlRecord record)
signal

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 record and can be modified before they will be inserted.

Referenced by insertRowIntoTable().

◆ beforeUpdate

QSqlTableModel::beforeUpdate ( int  row,
QSqlRecord record 
)
signal

This signal is emitted by 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() .

See also
QSqlRecord::isGenerated()

Referenced by updateRowInTable().

◆ clear()

void QSqlTableModel::clear ( void  )
virtual

Reimplemented Function

Reimplemented from QSqlQueryModel.

Definition at line 1325 of file qsqltablemodel.cpp.

Referenced by QSqlRelationalTableModel::clear(), and setTable().

1326 {
1328  d->clear();
1330 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
virtual void clear()
Clears the model and releases any acquired resource.
The QSqlTableModel class provides an editable data model for a single database table.

◆ data()

QVariant QSqlTableModel::data ( const QModelIndex idx,
int  role = Qt::DisplayRole 
) const
virtual

Reimplemented Function

Reimplemented from QSqlQueryModel.

Definition at line 457 of file qsqltablemodel.cpp.

Referenced by QSqlRelationalTableModel::data().

458 {
459  Q_D(const QSqlTableModel);
460  if (!index.isValid() || (role != Qt::DisplayRole && role != Qt::EditRole))
461  return QVariant();
462 
463  // Problem.. we need to use QSQM::indexInQuery to handle inserted columns
464  // but inserted rows we need to handle
465  // and indexInQuery is not virtual (grrr) so any values we pass to QSQM need
466  // to handle the insertedRows
468 
469  switch (d->strategy) {
470  case OnFieldChange:
471  case OnRowChange:
472  if (index.row() == d->insertIndex) {
473  if (item.column() < 0 || item.column() >= d->rec.count())
474  return QVariant();
475  return d->editBuffer.value(index.column());
476  }
477  if (d->editIndex == item.row()) {
478  if (d->editBuffer.isGenerated(item.column()))
479  return d->editBuffer.value(item.column());
480  }
481  break;
482  case OnManualSubmit:
483  if (d->cache.contains(index.row())) {
484  const QSqlTableModelPrivate::ModifiedRow row = d->cache.value(index.row());
485  if (row.rec.isGenerated(item.column()) || row.op == QSqlTableModelPrivate::Insert)
486  return row.rec.value(item.column());
487  }
488  break;
489  }
490 
491  // We need to handle row mapping here, but not column mapping
492  return QSqlQueryModel::data(index.sibling(item.row(), index.column()), role);
493 }
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
double d
Definition: qnumeric_p.h:62
QModelIndex sibling(int row, int column) const
Returns the sibling at row and column.
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const
Returns the index of the data in row and column with parent.
QVariant data(const QModelIndex &item, int role=Qt::DisplayRole) const
Returns the value for the specified item and role.
#define Q_D(Class)
Definition: qglobal.h:2482
bool isGenerated(int i) const
Returns true if the record has a field at position index and this field is to be generated (the defau...
Definition: qsqlrecord.cpp:519
int row() const
Returns the row this model index refers to.
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
The QModelIndex class is used to locate data in a data model.
QModelIndex indexInQuery(const QModelIndex &item) const
Returns the index of the value in the database result set for the given item in the model...
The QSqlTableModel class provides an editable data model for a single database table.
QVariant value(int i) const
Returns the value of the field located at position index in the record.
Definition: qsqlrecord.cpp:203
int column() const
Returns the column this model index refers to.

◆ database()

QSqlDatabase QSqlTableModel::database ( ) const

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

Definition at line 976 of file qsqltablemodel.cpp.

Referenced by QRelation::populateDictionary(), QRelation::populateModel(), and QSqlRelationalTableModel::selectStatement().

977 {
978  Q_D(const QSqlTableModel);
979  return d->db;
980 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.

◆ deleteRowFromTable()

bool QSqlTableModel::deleteRowFromTable ( int  row)
protectedvirtual

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

Definition at line 707 of file qsqltablemodel.cpp.

Referenced by removeRows(), and submitAll().

708 {
710  emit beforeDelete(row);
711 
712  const QSqlRecord whereValues = d->strategy == OnManualSubmit ? d->cache[row].primaryValues : d->primaryValues(row);
713  bool prepStatement = d->db.driver()->hasFeature(QSqlDriver::PreparedQueries);
714  QString stmt = d->db.driver()->sqlStatement(QSqlDriver::DeleteStatement,
715  d->tableName,
716  QSqlRecord(),
717  prepStatement);
718  QString where = d->db.driver()->sqlStatement(QSqlDriver::WhereStatement,
719  d->tableName,
720  whereValues,
721  prepStatement);
722 
723  if (stmt.isEmpty() || where.isEmpty()) {
724  d->error = QSqlError(QLatin1String("Unable to delete row"), QString(),
726  return false;
727  }
728  stmt.append(QLatin1Char(' ')).append(where);
729 
730  return d->exec(stmt, prepStatement, QSqlRecord() /* no new values */, whereValues);
731 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
double d
Definition: qnumeric_p.h:62
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
#define emit
Definition: qobjectdefs.h:76
QString & append(QChar c)
Definition: qstring.cpp:1777
The QSqlTableModel class provides an editable data model for a single database table.
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
void beforeDelete(int row)
This signal is emitted by deleteRowFromTable() before the row is deleted from the currently active da...

◆ editStrategy()

QSqlTableModel::EditStrategy QSqlTableModel::editStrategy ( ) const

Returns the current edit strategy.

See also
setEditStrategy()

Definition at line 886 of file qsqltablemodel.cpp.

887 {
888  Q_D(const QSqlTableModel);
889  return d->strategy;
890 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.

◆ fieldIndex()

int QSqlTableModel::fieldIndex ( const QString fieldName) const

Returns the index of the field fieldName, or -1 if no corresponding field exists in the model.

Definition at line 1037 of file qsqltablemodel.cpp.

1038 {
1039  Q_D(const QSqlTableModel);
1040  return d->rec.indexOf(fieldName);
1041 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.

◆ filter()

QString QSqlTableModel::filter ( ) const

Returns the currently set filter.

See also
setFilter(), select()

Definition at line 1297 of file qsqltablemodel.cpp.

Referenced by QSqlRelationalTableModel::selectStatement(), and setFilter().

1298 {
1299  Q_D(const QSqlTableModel);
1300  return d->filter;
1301 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.

◆ flags()

Qt::ItemFlags QSqlTableModel::flags ( const QModelIndex index) const
virtual

Reimplemented Function

Reimplemented from QAbstractItemModel.

Definition at line 1334 of file qsqltablemodel.cpp.

1335 {
1336  Q_D(const QSqlTableModel);
1337  if (index.internalPointer() || index.column() < 0 || index.column() >= d->rec.count()
1338  || index.row() < 0)
1339  return 0;
1340  if (d->rec.field(index.column()).isReadOnly())
1343 }
double d
Definition: qnumeric_p.h:62
void * internalPointer() const
Returns a void * pointer used by the model to associate the index with the internal data structure...
#define Q_D(Class)
Definition: qglobal.h:2482
int row() const
Returns the row this model index refers to.
The QSqlTableModel class provides an editable data model for a single database table.
int column() const
Returns the column this model index refers to.

◆ headerData()

QVariant QSqlTableModel::headerData ( int  section,
Qt::Orientation  orientation,
int  role = Qt::DisplayRole 
) const
virtual

Reimplemented Function

Reimplemented from QSqlQueryModel.

Definition at line 498 of file qsqltablemodel.cpp.

499 {
500  Q_D(const QSqlTableModel);
501  if (orientation == Qt::Vertical && role == Qt::DisplayRole) {
502  switch (d->strategy) {
503  case OnFieldChange:
504  case OnRowChange:
505  if (d->insertIndex == section)
506  return QLatin1String("*");
507  break;
508  case OnManualSubmit:
509  QSqlTableModelPrivate::Op op = d->cache.value(section).op;
511  return QLatin1String("*");
512  else if (op == QSqlTableModelPrivate::Delete)
513  return QLatin1String("!");
514  break;
515  }
516  }
517  return QSqlQueryModel::headerData(section, orientation, role);
518 }
double d
Definition: qnumeric_p.h:62
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
#define Q_D(Class)
Definition: qglobal.h:2482
QVariant headerData(int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const
Returns the header data for the given role in the section of the header with the specified orientatio...
The QSqlTableModel class provides an editable data model for a single database table.

◆ indexInQuery()

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

Definition at line 1272 of file qsqltablemodel.cpp.

Referenced by data(), removeRows(), setData(), and setRecord().

1273 {
1274  Q_D(const QSqlTableModel);
1275  const QModelIndex it = QSqlQueryModel::indexInQuery(item); // this adjusts columns only
1276  if (d->strategy == OnManualSubmit) {
1277  int rowOffset = 0;
1278  QSqlTableModelPrivate::CacheMap::ConstIterator i = d->cache.constBegin();
1279  while (i != d->cache.constEnd() && i.key() <= it.row()) {
1280  if (i.value().op == QSqlTableModelPrivate::Insert)
1281  ++rowOffset;
1282  ++i;
1283  }
1284  return createIndex(it.row() - rowOffset, it.column(), it.internalPointer());
1285  } else {
1286  if (d->insertIndex >= 0 && it.row() >= d->insertIndex)
1287  return createIndex(it.row() - 1, it.column(), it.internalPointer());
1288  }
1289  return it;
1290 }
QModelIndex indexInQuery(const QModelIndex &item) const
Returns the index of the value in the database result set for the given item in the model...
double d
Definition: qnumeric_p.h:62
void * internalPointer() const
Returns a void * pointer used by the model to associate the index with the internal data structure...
#define it(className, varName)
QModelIndex createIndex(int row, int column, void *data=0) const
Creates a model index for the given row and column with the internal pointer ptr. ...
#define Q_D(Class)
Definition: qglobal.h:2482
const_iterator ConstIterator
Qt-style synonym for QMap::const_iterator.
Definition: qmap.h:389
int row() const
Returns the row this model index refers to.
The QModelIndex class is used to locate data in a data model.
The QSqlTableModel class provides an editable data model for a single database table.
int column() const
Returns the column this model index refers to.

◆ insertRecord()

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(), removeRows()

Definition at line 1224 of file qsqltablemodel.cpp.

1225 {
1227  if (row < 0)
1228  row = rowCount();
1229  if (!insertRow(row, QModelIndex()))
1230  return false;
1231  if (!setRecord(row, record))
1232  return false;
1233  if (d->strategy == OnFieldChange || d->strategy == OnRowChange)
1234  return submit();
1235  return true;
1236 }
double d
Definition: qnumeric_p.h:62
int rowCount(const QModelIndex &parent=QModelIndex()) const
Reimplemented Function
#define Q_D(Class)
Definition: qglobal.h:2482
bool setRecord(int row, const QSqlRecord &record)
Sets the values at the specified row to the values of record.
bool insertRow(int row, const QModelIndex &parent=QModelIndex())
Inserts a single row before the given row in the child items of the parent specified.
bool submit()
This reimplemented slot is called by the item delegates when the user stopped editing the current row...
The QModelIndex class is used to locate data in a data model.
The QSqlTableModel class provides an editable data model for a single database table.

◆ insertRowIntoTable()

bool QSqlTableModel::insertRowIntoTable ( const QSqlRecord values)
protectedvirtual

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

Reimplemented in QSqlRelationalTableModel.

Definition at line 676 of file qsqltablemodel.cpp.

Referenced by QSqlRelationalTableModel::insertRowIntoTable(), and submitAll().

677 {
679  QSqlRecord rec = values;
680  emit beforeInsert(rec);
681 
682  bool prepStatement = d->db.driver()->hasFeature(QSqlDriver::PreparedQueries);
683  QString stmt = d->db.driver()->sqlStatement(QSqlDriver::InsertStatement, d->tableName,
684  rec, prepStatement);
685 
686  if (stmt.isEmpty()) {
687  d->error = QSqlError(QLatin1String("No Fields to update"), QString(),
689  return false;
690  }
691 
692  return d->exec(stmt, prepStatement, rec, QSqlRecord() /* no where values */);
693 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
double d
Definition: qnumeric_p.h:62
void beforeInsert(QSqlRecord &record)
This signal is emitted by insertRowIntoTable() before a new row is inserted into the currently active...
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
#define emit
Definition: qobjectdefs.h:76
quint16 values[128]
The QSqlTableModel class provides an editable data model for a single database table.

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

See also
primeInsert(), insertRecord()

Reimplemented from QAbstractItemModel.

Definition at line 1175 of file qsqltablemodel.cpp.

1176 {
1178  if (row < 0 || count <= 0 || row > rowCount() || parent.isValid())
1179  return false;
1180 
1181  switch (d->strategy) {
1182  case OnFieldChange:
1183  case OnRowChange:
1184  if (count != 1)
1185  return false;
1186  beginInsertRows(parent, row, row);
1187  d->insertIndex = row;
1188  // ### apply dangling changes...
1189  d->clearEditBuffer();
1190  emit primeInsert(row, d->editBuffer);
1191  break;
1192  case OnManualSubmit:
1193  beginInsertRows(parent, row, row + count - 1);
1194  if (!d->cache.isEmpty()) {
1196  while (it != d->cache.begin() && (--it).key() >= row) {
1197  int oldKey = it.key();
1198  const QSqlTableModelPrivate::ModifiedRow oldValue = it.value();
1199  d->cache.erase(it);
1200  it = d->cache.insert(oldKey + count, oldValue);
1201  }
1202  }
1203 
1204  for (int i = 0; i < count; ++i) {
1206  d->rec);
1207  emit primeInsert(row + i, d->cache[row + i].rec);
1208  }
1209  break;
1210  }
1211  endInsertRows();
1212  return true;
1213 }
double d
Definition: qnumeric_p.h:62
const Key & key() const
Returns the current item&#39;s key as a const reference.
Definition: qmap.h:250
int rowCount(const QModelIndex &parent=QModelIndex()) const
Reimplemented Function
#define it(className, varName)
void endInsertRows()
Ends a row insertion operation.
#define Q_D(Class)
Definition: qglobal.h:2482
void primeInsert(int row, QSqlRecord &record)
This signal is emitted by insertRows(), when an insertion is initiated in the given row of the curren...
T & value() const
Returns a modifiable reference to the current item&#39;s value.
Definition: qmap.h:251
#define emit
Definition: qobjectdefs.h:76
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
The QMap::iterator class provides an STL-style non-const iterator for QMap and QMultiMap.
Definition: qmap.h:233
int key
The QSqlTableModel class provides an editable data model for a single database table.
void beginInsertRows(const QModelIndex &parent, int first, int last)
Begins a row insertion operation.

◆ isDirty()

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.

Definition at line 527 of file qsqltablemodel.cpp.

528 {
529  Q_D(const QSqlTableModel);
530  if (!index.isValid())
531  return false;
532 
533  switch (d->strategy) {
534  case OnFieldChange:
535  return false;
536  case OnRowChange:
537  return index.row() == d->editIndex && d->editBuffer.isGenerated(index.column());
538  case OnManualSubmit: {
539  const QSqlTableModelPrivate::ModifiedRow row = d->cache.value(index.row());
540  return row.op == QSqlTableModelPrivate::Insert
543  && row.rec.isGenerated(index.column()));
544  }
545  }
546  return false;
547 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
bool isGenerated(int i) const
Returns true if the record has a field at position index and this field is to be generated (the defau...
Definition: qsqlrecord.cpp:519
int row() const
Returns the row this model index refers to.
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
The QSqlTableModel class provides an editable data model for a single database table.
int column() const
Returns the column this model index refers to.

◆ orderByClause()

QString QSqlTableModel::orderByClause ( ) const
protectedvirtual

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

See also
setSort(), selectStatement()

Reimplemented in QSqlRelationalTableModel.

Definition at line 1015 of file qsqltablemodel.cpp.

Referenced by QSqlRelationalTableModel::orderByClause(), and selectStatement().

1016 {
1017  Q_D(const QSqlTableModel);
1018  QString s;
1019  QSqlField f = d->rec.field(d->sortColumn);
1020  if (!f.isValid())
1021  return s;
1022 
1023  QString table = d->tableName;
1024  //we can safely escape the field because it would have been obtained from the database
1025  //and have the correct case
1026  QString field = d->db.driver()->escapeIdentifier(f.name(), QSqlDriver::FieldName);
1027  s.append(QLatin1String("ORDER BY ")).append(table).append(QLatin1Char('.')).append(field);
1028  s += d->sortOrder == Qt::AscendingOrder ? QLatin1String(" ASC") : QLatin1String(" DESC");
1029 
1030  return s;
1031 }
double d
Definition: qnumeric_p.h:62
bool isValid() const
Returns true if the field&#39;s variant type is valid; otherwise returns false.
Definition: qsqlfield.cpp:517
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
QString name() const
Returns the name of the field.
Definition: qsqlfield.cpp:380
QString & append(QChar c)
Definition: qstring.cpp:1777
The QSqlTableModel class provides an editable data model for a single database table.
The QSqlField class manipulates the fields in SQL database tables and views.
Definition: qsqlfield.h:56
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ primaryKey()

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

Definition at line 952 of file qsqltablemodel.cpp.

953 {
954  Q_D(const QSqlTableModel);
955  return d->primaryIndex;
956 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.

◆ primeInsert

void QSqlTableModel::primeInsert ( int  row,
QSqlRecord record 
)
signal

This signal is emitted by 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.

Referenced by insertRows().

◆ removeColumns()

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.

See also
removeRows()

Reimplemented from QSqlQueryModel.

Definition at line 1092 of file qsqltablemodel.cpp.

Referenced by QSqlRelationalTableModel::removeColumns().

1093 {
1095  if (parent.isValid() || column < 0 || column + count > d->rec.count())
1096  return false;
1097  for (int i = 0; i < count; ++i)
1098  d->rec.remove(column);
1099  if (d->query.isActive())
1100  return select();
1101  return true;
1102 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
The QSqlTableModel class provides an editable data model for a single database table.
virtual bool select()
Populates the model with data from the table that was set via setTable(), using the specified filter ...

◆ 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. When the edit strategy is OnManualSubmit signal emission is delayed until submitAll() is called.

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

See also
removeColumns(), insertRows()

Reimplemented from QAbstractItemModel.

Definition at line 1119 of file qsqltablemodel.cpp.

1120 {
1122  if (parent.isValid() || row < 0 || count <= 0)
1123  return false;
1124 
1125  int i;
1126  switch (d->strategy) {
1127  case OnFieldChange:
1128  case OnRowChange:
1129  for (i = 0; i < count; ++i) {
1130  if (row + i == d->insertIndex)
1131  d->revertInsertedRow();
1132  else if (!deleteRowFromTable(row + i))
1133  return false;
1134  }
1135  select();
1136  break;
1137  case OnManualSubmit:
1138  for (i = 0; i < count; ++i) {
1139  int idx = row + i;
1140  if (idx >= rowCount())
1141  return false;
1142  if (d->cache.value(idx).op == QSqlTableModelPrivate::Insert) {
1143  revertRow(idx);
1144  // Reverting a row means all the other cache entries have been adjusted downwards
1145  // so fake this by adjusting row
1146  --row;
1147  } else {
1148  d->cache[idx].op = QSqlTableModelPrivate::Delete;
1149  d->cache[idx].primaryValues = d->primaryValues(indexInQuery(createIndex(idx, 0)).row());
1150  emit headerDataChanged(Qt::Vertical, idx, idx);
1151  }
1152  }
1153  break;
1154  }
1155  return true;
1156 }
double d
Definition: qnumeric_p.h:62
int rowCount(const QModelIndex &parent=QModelIndex()) const
Reimplemented Function
QModelIndex createIndex(int row, int column, void *data=0) const
Creates a model index for the given row and column with the internal pointer ptr. ...
#define Q_D(Class)
Definition: qglobal.h:2482
#define emit
Definition: qobjectdefs.h:76
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
void headerDataChanged(Qt::Orientation orientation, int first, int last)
This signal is emitted whenever a header is changed.
virtual bool deleteRowFromTable(int row)
Deletes the given row from the currently active database table.
QModelIndex indexInQuery(const QModelIndex &item) const
Returns the index of the value in the database result set for the given item in the model...
The QSqlTableModel class provides an editable data model for a single database table.
virtual bool select()
Populates the model with data from the table that was set via setTable(), using the specified filter ...
virtual void revertRow(int row)
Reverts all changes for the specified row.

◆ revert

void QSqlTableModel::revert ( )
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.

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

Definition at line 839 of file qsqltablemodel.cpp.

840 {
842  if (d->strategy == OnRowChange)
843  revertAll();
844 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.
void revertAll()
Reverts all pending changes.

◆ revertAll

void QSqlTableModel::revertAll ( )
slot

Reverts all pending changes.

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

Definition at line 897 of file qsqltablemodel.cpp.

Referenced by revert(), select(), and setEditStrategy().

898 {
900  switch (d->strategy) {
901  case OnFieldChange:
902  break;
903  case OnRowChange:
904  if (d->editIndex != -1)
905  revertRow(d->editIndex);
906  else if (d->insertIndex != -1)
907  revertRow(d->insertIndex);
908  break;
909  case OnManualSubmit:
910  while (!d->cache.isEmpty())
911  revertRow(d->cache.constBegin().key());
912  break;
913  }
914 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.
virtual void revertRow(int row)
Reverts all changes for the specified row.

◆ revertRow()

void QSqlTableModel::revertRow ( int  row)
virtual

Reverts all changes for the specified row.

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

Definition at line 921 of file qsqltablemodel.cpp.

Referenced by removeRows(), revertAll(), and QSqlRelationalTableModel::revertRow().

922 {
923  if (row < 0)
924  return;
925 
927  switch (d->strategy) {
928  case OnFieldChange:
929  break;
930  case OnRowChange: {
931  if (d->editIndex == row) {
932  d->editBuffer.clear();
933  int oldIndex = d->editIndex;
934  d->editIndex = -1;
935  emit dataChanged(createIndex(oldIndex, 0), createIndex(oldIndex, columnCount() - 1));
936  } else if (d->insertIndex == row) {
937  d->revertInsertedRow();
938  }
939  break; }
940  case OnManualSubmit:
941  d->revertCachedRow(row);
942  break;
943  }
944 }
double d
Definition: qnumeric_p.h:62
QModelIndex createIndex(int row, int column, void *data=0) const
Creates a model index for the given row and column with the internal pointer ptr. ...
#define Q_D(Class)
Definition: qglobal.h:2482
int columnCount(const QModelIndex &parent=QModelIndex()) const
Reimplemented Function
#define emit
Definition: qobjectdefs.h:76
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
This signal is emitted whenever the data in an existing item changes.
The QSqlTableModel class provides an editable data model for a single database table.

◆ rowCount()

int QSqlTableModel::rowCount ( const QModelIndex parent = QModelIndex()) const
virtual

Reimplemented Function

Reimplemented from QSqlQueryModel.

Definition at line 1240 of file qsqltablemodel.cpp.

Referenced by insertRecord(), insertRows(), QRelation::populateDictionary(), removeRows(), setData(), setRecord(), and updateRowInTable().

1241 {
1242  Q_D(const QSqlTableModel);
1243 
1244  if (parent.isValid())
1245  return 0;
1246 
1247  int rc = QSqlQueryModel::rowCount();
1248  if (d->strategy == OnManualSubmit) {
1249  for (QSqlTableModelPrivate::CacheMap::ConstIterator it = d->cache.constBegin();
1250  it != d->cache.constEnd(); ++it) {
1251  if (it.value().op == QSqlTableModelPrivate::Insert)
1252  ++rc;
1253  }
1254  } else if (d->insertIndex >= 0) {
1255  ++rc;
1256  }
1257  return rc;
1258 }
double d
Definition: qnumeric_p.h:62
int rowCount(const QModelIndex &parent=QModelIndex()) const
If the database supports returning the size of a query (see QSqlDriver::hasFeature()), the number of rows of the current query is returned.
#define it(className, varName)
#define Q_D(Class)
Definition: qglobal.h:2482
const_iterator ConstIterator
Qt-style synonym for QMap::const_iterator.
Definition: qmap.h:389
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
The QSqlTableModel class provides an editable data model for a single database table.

◆ select()

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.

Note
Calling select() will revert any unsubmitted changes and remove any inserted columns.
See also
setTable(), setFilter(), selectStatement()

Reimplemented in QRelatedTableModel, and QSqlRelationalTableModel.

Definition at line 435 of file qsqltablemodel.cpp.

Referenced by removeColumns(), removeRows(), QSqlRelationalTableModel::select(), QRelatedTableModel::select(), setData(), setFilter(), sort(), and submitAll().

436 {
439  if (query.isEmpty())
440  return false;
441 
442  revertAll();
443  QSqlQuery qu(query, d->db);
444  setQuery(qu);
445 
446  if (!qu.isActive() || lastError().isValid()) {
447  // something went wrong - revert to non-select state
448  d->initRecordAndPrimaryIndex();
449  return false;
450  }
451  return true;
452 }
double d
Definition: qnumeric_p.h:62
virtual QString selectStatement() const
Returns the SQL SELECT statement used internally to populate the model.
QSqlError lastError() const
Returns information about the last error that occurred on the database.
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition: qsqlquery.h:63
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
QSqlQuery query() const
Returns the QSqlQuery associated with this model.
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
void setQuery(const QSqlQuery &query)
This function simply calls QSqlQueryModel::setQuery(query).
The QSqlTableModel class provides an editable data model for a single database table.
bool isValid() const
Returns true if an error is set, otherwise false.
Definition: qsqlerror.cpp:254
void revertAll()
Reverts all pending changes.

◆ selectStatement()

QString QSqlTableModel::selectStatement ( ) const
protectedvirtual

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

Reimplemented in QSqlRelationalTableModel.

Definition at line 1050 of file qsqltablemodel.cpp.

Referenced by select(), and QSqlRelationalTableModel::selectStatement().

1051 {
1052  Q_D(const QSqlTableModel);
1053  QString query;
1054  if (d->tableName.isEmpty()) {
1055  d->error = QSqlError(QLatin1String("No table name given"), QString(),
1057  return query;
1058  }
1059  if (d->rec.isEmpty()) {
1060  d->error = QSqlError(QLatin1String("Unable to find table ") + d->tableName, QString(),
1062  return query;
1063  }
1064 
1065  query = d->db.driver()->sqlStatement(QSqlDriver::SelectStatement,
1066  d->tableName,
1067  d->rec,
1068  false);
1069  if (query.isEmpty()) {
1070  d->error = QSqlError(QLatin1String("Unable to select fields from table ") + d->tableName,
1072  return query;
1073  }
1074  if (!d->filter.isEmpty())
1075  query.append(QLatin1String(" WHERE ")).append(d->filter);
1076  QString orderBy(orderByClause());
1077  if (!orderBy.isEmpty())
1078  query.append(QLatin1Char(' ')).append(orderBy);
1079 
1080  return query;
1081 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
double d
Definition: qnumeric_p.h:62
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
QSqlQuery query() const
Returns the QSqlQuery associated with this model.
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal...
Definition: qstring.h:654
virtual QString orderByClause() const
Returns an SQL ORDER BY clause based on the currently set sort order.
QString & append(QChar c)
Definition: qstring.cpp:1777
The QSqlTableModel class provides an editable data model for a single database table.
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ setData()

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.

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

Reimplemented from QAbstractItemModel.

Definition at line 559 of file qsqltablemodel.cpp.

Referenced by QSqlRelationalTableModel::setData().

560 {
562  if (role != Qt::EditRole)
563  return QSqlQueryModel::setData(index, value, role);
564 
565  if (!index.isValid() || index.column() >= d->rec.count() || index.row() >= rowCount())
566  return false;
567 
568  bool isOk = true;
569  switch (d->strategy) {
570  case OnFieldChange: {
571  if (index.row() == d->insertIndex) {
572  QSqlTableModelPrivate::setGeneratedValue(d->editBuffer, index.column(), value);
573  return true;
574  }
575  d->clearEditBuffer();
576  QSqlTableModelPrivate::setGeneratedValue(d->editBuffer, index.column(), value);
577  isOk = updateRowInTable(index.row(), d->editBuffer);
578  if (isOk)
579  select();
580  emit dataChanged(index, index);
581  break; }
582  case OnRowChange:
583  if (index.row() == d->insertIndex) {
584  QSqlTableModelPrivate::setGeneratedValue(d->editBuffer, index.column(), value);
585  return true;
586  }
587  if (d->editIndex != index.row()) {
588  if (d->editIndex != -1)
589  submit();
590  d->clearEditBuffer();
591  }
592  QSqlTableModelPrivate::setGeneratedValue(d->editBuffer, index.column(), value);
593  d->editIndex = index.row();
594  emit dataChanged(index, index);
595  break;
596  case OnManualSubmit: {
597  QSqlTableModelPrivate::ModifiedRow &row = d->cache[index.row()];
598  if (row.op == QSqlTableModelPrivate::None) {
600  row.rec = d->rec;
602  row.primaryValues = d->primaryValues(indexInQuery(index).row());
603  }
605  emit dataChanged(index, index);
606  break; }
607  }
608  return isOk;
609 }
static void clearGenerated(QSqlRecord &rec)
double d
Definition: qnumeric_p.h:62
static void setGeneratedValue(QSqlRecord &rec, int c, QVariant v)
int rowCount(const QModelIndex &parent=QModelIndex()) const
Reimplemented Function
virtual bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole)
Sets the role data for the item at index to value.
#define Q_D(Class)
Definition: qglobal.h:2482
int row() const
Returns the row this model index refers to.
#define emit
Definition: qobjectdefs.h:76
virtual bool updateRowInTable(int row, const QSqlRecord &values)
Updates the given row in the currently active database table with the specified values.
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
bool submit()
This reimplemented slot is called by the item delegates when the user stopped editing the current row...
QModelIndex indexInQuery(const QModelIndex &item) const
Returns the index of the value in the database result set for the given item in the model...
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
This signal is emitted whenever the data in an existing item changes.
The QSqlTableModel class provides an editable data model for a single database table.
virtual bool select()
Populates the model with data from the table that was set via setTable(), using the specified filter ...
int column() const
Returns the column this model index refers to.

◆ setEditStrategy()

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(), revertAll()

Definition at line 874 of file qsqltablemodel.cpp.

875 {
877  revertAll();
878  d->strategy = strategy;
879 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.
void revertAll()
Reverts all pending changes.

◆ setFilter()

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

Definition at line 1315 of file qsqltablemodel.cpp.

1316 {
1318  d->filter = filter;
1319  if (d->query.isActive())
1320  select();
1321 }
double d
Definition: qnumeric_p.h:62
QString filter() const
Returns the currently set filter.
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.
virtual bool select()
Populates the model with data from the table that was set via setTable(), using the specified filter ...

◆ setPrimaryKey()

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

Definition at line 967 of file qsqltablemodel.cpp.

968 {
970  d->primaryIndex = key;
971 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
int key
The QSqlTableModel class provides an editable data model for a single database table.

◆ setQuery()

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

Definition at line 618 of file qsqltablemodel.cpp.

Referenced by select().

619 {
621 }
void setQuery(const QSqlQuery &query)
Resets the model and sets the data provider to be the given query.

◆ setRecord()

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

Definition at line 1352 of file qsqltablemodel.cpp.

Referenced by insertRecord().

1353 {
1355  Q_ASSERT_X(row >= 0, "QSqlTableModel::setRecord()", "Cannot set a record to a row less than 0");
1356  if (row >= rowCount())
1357  return false;
1358 
1359  bool isOk = true;
1360  switch (d->strategy) {
1361  case OnFieldChange:
1362  case OnRowChange:
1363  return d->setRecord(row, record);
1364  case OnManualSubmit: {
1365  QSqlTableModelPrivate::ModifiedRow &mrow = d->cache[row];
1366  if (mrow.op == QSqlTableModelPrivate::None) {
1368  mrow.rec = d->rec;
1370  mrow.primaryValues = d->primaryValues(indexInQuery(createIndex(row, 0)).row());
1371  }
1372  QString fieldName;
1373  for (int i = 0; i < record.count(); ++i) {
1374  fieldName = record.fieldName(i);
1375  if (d->db.driver()->isIdentifierEscaped(fieldName, QSqlDriver::FieldName))
1376  fieldName = d->db.driver()->stripDelimiters(fieldName, QSqlDriver::FieldName);
1377  int idx = mrow.rec.indexOf(fieldName);
1378  if (idx == -1) {
1379  isOk = false;
1380  } else {
1381  mrow.rec.setValue(idx, record.value(i));
1382  mrow.rec.setGenerated(idx, record.isGenerated(i));
1383  }
1384  }
1385 
1386  if (isOk)
1387  emit dataChanged(createIndex(row, 0), createIndex(row, columnCount() - 1));
1388  return isOk; }
1389  }
1390  return false;
1391 }
static void clearGenerated(QSqlRecord &rec)
double d
Definition: qnumeric_p.h:62
int rowCount(const QModelIndex &parent=QModelIndex()) const
Reimplemented Function
QModelIndex createIndex(int row, int column, void *data=0) const
Creates a model index for the given row and column with the internal pointer ptr. ...
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
bool isGenerated(int i) const
Returns true if the record has a field at position index and this field is to be generated (the defau...
Definition: qsqlrecord.cpp:519
int columnCount(const QModelIndex &parent=QModelIndex()) const
Reimplemented Function
#define emit
Definition: qobjectdefs.h:76
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
int count() const
Returns the number of fields in the record.
Definition: qsqlrecord.cpp:573
QModelIndex indexInQuery(const QModelIndex &item) const
Returns the index of the value in the database result set for the given item in the model...
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
This signal is emitted whenever the data in an existing item changes.
The QSqlTableModel class provides an editable data model for a single database table.
void setValue(int i, const QVariant &val)
Sets the value of the field at position index to val.
Definition: qsqlrecord.cpp:585
QString fieldName(int i) const
Returns the name of the field at position index.
Definition: qsqlrecord.cpp:232
QVariant value(int i) const
Returns the value of the field located at position index in the record.
Definition: qsqlrecord.cpp:203
int indexOf(const QString &name) const
Returns the position of the field called name within the record, or -1 if it cannot be found...
Definition: qsqlrecord.cpp:246
void setGenerated(const QString &name, bool generated)
Sets the generated flag for the field called name to generated.
Definition: qsqlrecord.cpp:420

◆ setSort()

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

Definition at line 1002 of file qsqltablemodel.cpp.

Referenced by sort().

1003 {
1005  d->sortColumn = column;
1006  d->sortOrder = order;
1007 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.

◆ setTable()

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

Reimplemented in QSqlRelationalTableModel.

Definition at line 404 of file qsqltablemodel.cpp.

Referenced by QRelation::populateModel(), and QSqlRelationalTableModel::setTable().

405 {
407  clear();
408  d->tableName = tableName;
409  d->initRecordAndPrimaryIndex();
410  d->initColOffsets(d->rec.count());
411 
412  if (d->rec.count() == 0)
413  d->error = QSqlError(QLatin1String("Unable to find table ") + d->tableName, QString(),
415 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
double d
Definition: qnumeric_p.h:62
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
void clear()
Reimplemented Function
QString tableName() const
Returns the name of the currently selected table.
The QSqlTableModel class provides an editable data model for a single database table.

◆ sort()

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.

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

Reimplemented from QAbstractItemModel.

Definition at line 989 of file qsqltablemodel.cpp.

990 {
991  setSort(column, order);
992  select();
993 }
virtual bool select()
Populates the model with data from the table that was set via setTable(), using the specified filter ...
virtual void setSort(int column, Qt::SortOrder order)
Sets the sort order for column to order.

◆ submit

bool QSqlTableModel::submit ( )
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.

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

Definition at line 819 of file qsqltablemodel.cpp.

Referenced by insertRecord(), and setData().

820 {
822  if (d->strategy == OnRowChange || d->strategy == OnFieldChange)
823  return submitAll();
824  return true;
825 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.
bool submitAll()
Submits all pending changes and returns true on success.

◆ submitAll

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

Definition at line 748 of file qsqltablemodel.cpp.

Referenced by submit().

749 {
751 
752  switch (d->strategy) {
753  case OnFieldChange:
754  if (d->insertIndex == -1)
755  return true;
756  // else fall through
757  case OnRowChange:
758  if (d->editBuffer.isEmpty())
759  return true;
760  if (d->insertIndex != -1) {
761  if (!insertRowIntoTable(d->editBuffer))
762  return false;
763  d->bottom = d->bottom.sibling(d->bottom.row() + 1, d->bottom.column());
764  } else {
765  if (!updateRowInTable(d->editIndex, d->editBuffer))
766  return false;
767  }
768  d->clearEditBuffer();
769  d->editIndex = -1;
770  d->insertIndex = -1;
771  return select();
772  case OnManualSubmit:
773  for (QSqlTableModelPrivate::CacheMap::ConstIterator it = d->cache.constBegin();
774  it != d->cache.constEnd(); ++it) {
775  switch (it.value().op) {
777  if (!insertRowIntoTable(it.value().rec))
778  return false;
779  d->bottom = d->bottom.sibling(d->bottom.row() + 1, d->bottom.column());
780  break;
782  if (!updateRowInTable(it.key(), it.value().rec))
783  return false;
784  break;
786  if (!deleteRowFromTable(it.key()))
787  return false;
788  break;
790  Q_ASSERT_X(false, "QSqlTableModel::submitAll()", "Invalid cache operation");
791  break;
792  }
793  }
794  d->clearCache();
795  return select();
796  }
797  return false;
798 }
double d
Definition: qnumeric_p.h:62
#define it(className, varName)
#define Q_D(Class)
Definition: qglobal.h:2482
const_iterator ConstIterator
Qt-style synonym for QMap::const_iterator.
Definition: qmap.h:389
virtual bool insertRowIntoTable(const QSqlRecord &values)
Inserts the values values into the currently active database table.
virtual bool updateRowInTable(int row, const QSqlRecord &values)
Updates the given row in the currently active database table with the specified values.
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
virtual bool deleteRowFromTable(int row)
Deletes the given row from the currently active database table.
The QSqlTableModel class provides an editable data model for a single database table.
virtual bool select()
Populates the model with data from the table that was set via setTable(), using the specified filter ...

◆ tableName()

QString QSqlTableModel::tableName ( ) const

Returns the name of the currently selected table.

Definition at line 420 of file qsqltablemodel.cpp.

Referenced by QSqlRelationalTableModelPrivate::QSqlRelationalTableModelPrivate(), QSqlRelationalTableModel::selectStatement(), and setTable().

421 {
422  Q_D(const QSqlTableModel);
423  return d->tableName;
424 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlTableModel class provides an editable data model for a single database table.

◆ updateRowInTable()

bool QSqlTableModel::updateRowInTable ( int  row,
const QSqlRecord values 
)
protectedvirtual

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

Reimplemented in QSqlRelationalTableModel.

Definition at line 639 of file qsqltablemodel.cpp.

Referenced by setData(), submitAll(), and QSqlRelationalTableModel::updateRowInTable().

640 {
642  QSqlRecord rec(values);
643  emit beforeUpdate(row, rec);
644 
645  const QSqlRecord whereValues = d->strategy == OnManualSubmit ? d->cache[row].primaryValues : d->primaryValues(row);
646  bool prepStatement = d->db.driver()->hasFeature(QSqlDriver::PreparedQueries);
647  QString stmt = d->db.driver()->sqlStatement(QSqlDriver::UpdateStatement, d->tableName,
648  rec, prepStatement);
649  QString where = d->db.driver()->sqlStatement(QSqlDriver::WhereStatement, d->tableName,
650  whereValues, prepStatement);
651 
652  if (stmt.isEmpty() || where.isEmpty() || row < 0 || row >= rowCount()) {
653  d->error = QSqlError(QLatin1String("No Fields to update"), QString(),
655  return false;
656  }
657  stmt.append(QLatin1Char(' ')).append(where);
658 
659  return d->exec(stmt, prepStatement, rec, whereValues);
660 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
double d
Definition: qnumeric_p.h:62
int rowCount(const QModelIndex &parent=QModelIndex()) const
Reimplemented Function
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
#define emit
Definition: qobjectdefs.h:76
QString & append(QChar c)
Definition: qstring.cpp:1777
void beforeUpdate(int row, QSqlRecord &record)
This signal is emitted by updateRowInTable() before the row is updated in the currently active databa...
The QSqlTableModel class provides an editable data model for a single database table.
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

The documentation for this class was generated from the following files: