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

The QSqlRelationalTableModel class provides an editable data model for a single database table, with foreign key support. More...

#include <qsqlrelationaltablemodel.h>

Inheritance diagram for QSqlRelationalTableModel:
QSqlTableModel QSqlQueryModel QAbstractTableModel QAbstractItemModel QObject

Public Types

enum  JoinMode { InnerJoin, LeftJoin }
 This enum specifies the type of mode to use when joining two tables. More...
 
- Public Types inherited from QSqlTableModel
enum  EditStrategy { OnFieldChange, OnRowChange, OnManualSubmit }
 This enum type describes which strategy to choose when editing values in the database. More...
 

Public Slots

void revertRow (int row)
 Reimplemented Function More...
 
- Public Slots inherited from QSqlTableModel
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...
 

Public Functions

void clear ()
 Reimplemented Function More...
 
QVariant data (const QModelIndex &item, int role=Qt::DisplayRole) const
 Reimplemented Function More...
 
 QSqlRelationalTableModel (QObject *parent=0, QSqlDatabase db=QSqlDatabase())
 Creates an empty QSqlRelationalTableModel and sets the parent to parent and the database connection to db. More...
 
QSqlRelation relation (int column) const
 Returns the relation for the column column, or an invalid relation if no relation is set. More...
 
virtual QSqlTableModelrelationModel (int column) const
 Returns a QSqlTableModel object for accessing the table for which column is a foreign key, or 0 if there is no relation for the given column. More...
 
bool removeColumns (int column, int count, const QModelIndex &parent=QModelIndex())
 Reimplemented Function More...
 
bool select ()
 Reimplemented Function More...
 
bool setData (const QModelIndex &item, const QVariant &value, int role=Qt::EditRole)
 Sets the data for the role in the item with the specified index to the value given. More...
 
void setJoinMode (QSqlRelationalTableModel::JoinMode joinMode)
 Sets the SQL join mode to the value given by joinMode to show or hide rows with NULL foreign keys. More...
 
virtual void setRelation (int column, const QSqlRelation &relation)
 Lets the specified column be a foreign index specified by relation. More...
 
void setTable (const QString &tableName)
 Reimplemented Function More...
 
virtual ~QSqlRelationalTableModel ()
 Destroys the object and frees any allocated resources. More...
 
- Public Functions inherited from QSqlTableModel
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...
 
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...
 
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

bool insertRowIntoTable (const QSqlRecord &values)
 Reimplemented Function More...
 
QString orderByClause () const
 Reimplemented Function More...
 
QString selectStatement () const
 Reimplemented Function More...
 
bool updateRowInTable (int row, const QSqlRecord &values)
 Reimplemented Function More...
 
- Protected Functions inherited from QSqlTableModel
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...
 
 QSqlTableModel (QSqlTableModelPrivate &dd, QObject *parent=0, QSqlDatabase db=QSqlDatabase())
 
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...
 
- 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

- Signals inherited from QSqlTableModel
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...
 
- 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 QSqlRelationalTableModel class provides an editable data model for a single database table, with foreign key support.

Attention
Module: QtSql

QSqlRelationalTableModel acts like QSqlTableModel, but allows columns to be set as foreign keys into other database tables.

noforeignkeys.png
foreignkeys.png

The screenshot on the left shows a plain QSqlTableModel in a QTableView. Foreign keys (city and country) aren't resolved to human-readable values. The screenshot on the right shows a QSqlRelationalTableModel, with foreign keys resolved into human-readable text strings.

The following code snippet shows how the QSqlRelationalTableModel was set up:

model->setTable("employee");
model->setRelation(2, QSqlRelation("city", "id", "name"));
model->setRelation(3, QSqlRelation("country", "id", "name"));

The setRelation() function calls establish a relationship between two tables. The first call specifies that column 2 in table employee is a foreign key that maps with field id of table city, and that the view should present the city's name field to the user. The second call does something similar with column 3.

If you use a read-write QSqlRelationalTableModel, you probably want to use QSqlRelationalDelegate on the view. Unlike the default delegate, QSqlRelationalDelegate provides a combobox for fields that are foreign keys into other tables. To use the class, simply call QAbstractItemView::setItemDelegate() on the view with an instance of QSqlRelationalDelegate:

QTableView *view = new QTableView;
view->setModel(model);

The sql/relationaltablemodel example illustrates how to use QSqlRelationalTableModel in conjunction with QSqlRelationalDelegate to provide tables with foreign key support.

relationaltable.png

Notes:

See also
QSqlRelation, QSqlRelationalDelegate, {Relational Table Model Example}

Definition at line 74 of file qsqlrelationaltablemodel.h.

Enumerations

◆ JoinMode

This enum specifies the type of mode to use when joining two tables.

Since
4.8
  • InnerJoin Inner join mode, return rows when there is at least one match in both tables.
  • LeftJoin Left join mode, returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).
See also
QSqlRelationalTableModel::setJoinMode()
Enumerator
InnerJoin 
LeftJoin 

Definition at line 79 of file qsqlrelationaltablemodel.h.

Constructors and Destructors

◆ QSqlRelationalTableModel()

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

Creates an empty QSqlRelationalTableModel and sets the parent to parent and the database connection to db.

If db is not valid, the default database connection will be used.

Definition at line 438 of file qsqlrelationaltablemodel.cpp.

440 {
441 }
QSqlTableModel(QObject *parent=0, QSqlDatabase db=QSqlDatabase())
Creates an empty QSqlTableModel and sets the parent to parent and the database connection to db...

◆ ~QSqlRelationalTableModel()

QSqlRelationalTableModel::~QSqlRelationalTableModel ( )
virtual

Destroys the object and frees any allocated resources.

Definition at line 446 of file qsqlrelationaltablemodel.cpp.

447 {
448 }

Functions

◆ clear()

void QSqlRelationalTableModel::clear ( void  )
virtual

Reimplemented Function

Reimplemented from QSqlQueryModel.

Definition at line 728 of file qsqlrelationaltablemodel.cpp.

729 {
731  d->clearChanges();
732  d->relations.clear();
734 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
#define Q_D(Class)
Definition: qglobal.h:2482
void clear()
Reimplemented Function

◆ data()

QVariant QSqlRelationalTableModel::data ( const QModelIndex item,
int  role = Qt::DisplayRole 
) const
virtual

Reimplemented Function

Reimplemented from QSqlQueryModel.

Definition at line 453 of file qsqlrelationaltablemodel.cpp.

454 {
456 
457  if (role == Qt::DisplayRole && index.column() >= 0 && index.column() < d->relations.count() &&
458  d->relations.value(index.column()).isValid()) {
459  QRelation &relation = d->relations[index.column()];
460  if (!relation.isDictionaryInitialized())
461  relation.populateDictionary();
462 
463  //only perform a dictionary lookup for the display value
464  //when the value at index has been changed or added.
465  //At an unmodified index, the underlying model will
466  //already have the correct display value.
467  QVariant v;
468  switch (d->strategy) {
469  case OnFieldChange:
470  break;
471  case OnRowChange:
472  if ((index.row() == d->editIndex || index.row() == d->insertIndex)
473  && d->editBuffer.isGenerated(index.column()))
474  v = d->editBuffer.value(index.column());
475  break;
476  case OnManualSubmit:
477  const QSqlTableModelPrivate::ModifiedRow row = d->cache.value(index.row());
479  v = row.rec.value(index.column());
480  break;
481  }
482  if (v.isValid())
483  return relation.dictionary[v.toString()];
484  }
485  return QSqlTableModel::data(index, role);
486 }
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
The QSqlRelationalTableModel class provides an editable data model for a single database table...
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const
Returns the index of the data in row and column with parent.
QString toString() const
Returns the variant as a QString if the variant has type() String , Bool , ByteArray ...
Definition: qvariant.cpp:2270
#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.
QSqlRelation relation(int column) const
Returns the relation for the column column, or an invalid relation if no relation is set...
bool isValid() const
Returns true if the storage type of this variant is not QVariant::Invalid; otherwise returns false...
Definition: qvariant.h:485
QVariant data(const QModelIndex &idx, int role=Qt::DisplayRole) const
Reimplemented Function
QVariant value(int i) const
Returns the value of the field located at position index in the record.
Definition: qsqlrecord.cpp:203
QHash< QString, QVariant > dictionary
int column() const
Returns the column this model index refers to.

◆ insertRowIntoTable()

bool QSqlRelationalTableModel::insertRowIntoTable ( const QSqlRecord values)
protectedvirtual

Reimplemented Function

Reimplemented from QSqlTableModel.

Definition at line 828 of file qsqlrelationaltablemodel.cpp.

829 {
831 
832  QSqlRecord rec = values;
833  d->translateFieldNames(0, rec);
834 
836 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
#define Q_D(Class)
Definition: qglobal.h:2482
virtual bool insertRowIntoTable(const QSqlRecord &values)
Inserts the values values into the currently active database table.
quint16 values[128]

◆ orderByClause()

QString QSqlRelationalTableModel::orderByClause ( ) const
protectedvirtual

Reimplemented Function

Reimplemented from QSqlTableModel.

Definition at line 841 of file qsqlrelationaltablemodel.cpp.

Referenced by selectStatement().

842 {
844 
845  const QSqlRelation rel = d->relations.value(d->sortColumn).rel;
846  if (!rel.isValid())
848 
849  QString s = QLatin1String("ORDER BY ");
850  s.append(d->relationField(QLatin1String("relTblAl_") + QString::number(d->sortColumn),
851  rel.displayColumn()));
852  s += d->sortOrder == Qt::AscendingOrder ? QLatin1String(" ASC") : QLatin1String(" DESC");
853  return s;
854 }
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qstring.cpp:6448
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
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
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.
The QSqlRelation class stores information about an SQL foreign key.
bool isValid() const
Returns true if the QSqlRelation object is valid; otherwise returns false.
QString & append(QChar c)
Definition: qstring.cpp:1777
QString displayColumn() const
Returns the column from table tableName() that should be presented to the user instead of a foreign k...

◆ relation()

QSqlRelation QSqlRelationalTableModel::relation ( int  column) const

Returns the relation for the column column, or an invalid relation if no relation is set.

See also
setRelation(), QSqlRelation::isValid()

Definition at line 552 of file qsqlrelationaltablemodel.cpp.

Referenced by data(), relationModel(), selectStatement(), and setData().

553 {
555  return d->relations.value(column).rel;
556 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
#define Q_D(Class)
Definition: qglobal.h:2482

◆ relationModel()

QSqlTableModel * QSqlRelationalTableModel::relationModel ( int  column) const
virtual

Returns a QSqlTableModel object for accessing the table for which column is a foreign key, or 0 if there is no relation for the given column.

The returned object is owned by the QSqlRelationalTableModel.

See also
setRelation(), relation()

Definition at line 702 of file qsqlrelationaltablemodel.cpp.

703 {
705  if ( column < 0 || column >= d->relations.count())
706  return 0;
707 
708  QRelation &relation = const_cast<QSqlRelationalTableModelPrivate *>(d)->relations[column];
709  if (!relation.isValid())
710  return 0;
711 
712  if (!relation.model)
713  relation.populateModel();
714  return relation.model;
715 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
#define Q_D(Class)
Definition: qglobal.h:2482
QRelatedTableModel * model
QSqlRelation relation(int column) const
Returns the relation for the column column, or an invalid relation if no relation is set...

◆ removeColumns()

bool QSqlRelationalTableModel::removeColumns ( int  column,
int  count,
const QModelIndex parent = QModelIndex() 
)
virtual

Reimplemented Function

Reimplemented from QSqlQueryModel.

Definition at line 859 of file qsqlrelationaltablemodel.cpp.

860 {
862 
863  if (parent.isValid() || column < 0 || column + count > d->rec.count())
864  return false;
865 
866  for (int i = 0; i < count; ++i) {
867  d->baseRec.remove(column);
868  if (d->relations.count() > column)
869  d->relations.remove(column);
870  }
871  return QSqlTableModel::removeColumns(column, count, parent);
872 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
#define Q_D(Class)
Definition: qglobal.h:2482
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
bool removeColumns(int column, int count, const QModelIndex &parent=QModelIndex())
Removes count columns from the parent model, starting at index column.

◆ revertRow

void QSqlRelationalTableModel::revertRow ( int  row)
slot

Reimplemented Function

Definition at line 720 of file qsqlrelationaltablemodel.cpp.

721 {
723 }
virtual void revertRow(int row)
Reverts all changes for the specified row.

◆ select()

bool QSqlRelationalTableModel::select ( )
virtual

Reimplemented Function

Reimplemented from QSqlTableModel.

Definition at line 776 of file qsqlrelationaltablemodel.cpp.

777 {
778  return QSqlTableModel::select();
779 }
virtual bool select()
Populates the model with data from the table that was set via setTable(), using the specified filter ...

◆ selectStatement()

QString QSqlRelationalTableModel::selectStatement ( ) const
protectedvirtual

Reimplemented Function

Reimplemented from QSqlTableModel.

Definition at line 571 of file qsqlrelationaltablemodel.cpp.

572 {
574  QString query;
575 
576  if (tableName().isEmpty())
577  return query;
578  if (d->relations.isEmpty())
580 
581  QString tList;
582  QString fList;
583  QString where;
584 
585  QSqlRecord rec = d->baseRec;
586  QStringList tables;
587  const QRelation nullRelation;
588 
589  // Count how many times each field name occurs in the record
590  QHash<QString, int> fieldNames;
591  QStringList fieldList;
592  for (int i = 0; i < rec.count(); ++i) {
593  QSqlRelation relation = d->relations.value(i, nullRelation).rel;
594  QString name;
595  if (relation.isValid())
596  {
597  // Count the display column name, not the original foreign key
598  name = relation.displayColumn();
599  if (d->db.driver()->isIdentifierEscaped(name, QSqlDriver::FieldName))
600  name = d->db.driver()->stripDelimiters(name, QSqlDriver::FieldName);
601 
602  QSqlRecord rec = database().record(relation.tableName());
603  for (int i = 0; i < rec.count(); ++i) {
604  if (name.compare(rec.fieldName(i), Qt::CaseInsensitive) == 0) {
605  name = rec.fieldName(i);
606  break;
607  }
608  }
609  }
610  else
611  name = rec.fieldName(i);
612  fieldNames.insert(name, fieldNames.value(name, 0) + 1);
613  fieldList.append(name);
614  }
615 
616  for (int i = 0; i < rec.count(); ++i) {
617  QSqlRelation relation = d->relations.value(i, nullRelation).rel;
618  if (relation.isValid()) {
619  QString relTableAlias = QString::fromLatin1("relTblAl_%1").arg(i);
620  if (!fList.isEmpty())
621  fList.append(QLatin1String(", "));
622  fList.append(d->relationField(relTableAlias,relation.displayColumn()));
623 
624  // If there are duplicate field names they must be aliased
625  if (fieldNames.value(fieldList[i]) > 1) {
626  QString relTableName = relation.tableName().section(QChar::fromLatin1('.'), -1, -1);
627  if (d->db.driver()->isIdentifierEscaped(relTableName, QSqlDriver::TableName))
628  relTableName = d->db.driver()->stripDelimiters(relTableName, QSqlDriver::TableName);
629  QString displayColumn = relation.displayColumn();
630  if (d->db.driver()->isIdentifierEscaped(displayColumn, QSqlDriver::FieldName))
631  displayColumn = d->db.driver()->stripDelimiters(displayColumn, QSqlDriver::FieldName);
632  fList.append(QString::fromLatin1(" AS %1_%2_%3").arg(relTableName).arg(displayColumn).arg(fieldNames.value(fieldList[i])));
633  fieldNames.insert(fieldList[i], fieldNames.value(fieldList[i])-1);
634  }
635 
636  if (d->joinMode == QSqlRelationalTableModel::InnerJoin) {
637  // this needs fixing!! the below if is borken.
638  // Use LeftJoin mode if you want correct behavior
639  tables.append(relation.tableName().append(QLatin1Char(' ')).append(relTableAlias));
640  if(!where.isEmpty())
641  where.append(QLatin1String(" AND "));
642  where.append(d->relationField(tableName(), d->db.driver()->escapeIdentifier(rec.fieldName(i), QSqlDriver::FieldName)));
643  where.append(QLatin1String(" = "));
644  where.append(d->relationField(relTableAlias, relation.indexColumn()));
645  } else {
646  tables.append(QLatin1String(" LEFT JOIN"));
647  tables.append(relation.tableName().append(QLatin1Char(' ')).append(relTableAlias));
648  tables.append(QLatin1String("ON"));
649 
650  QString clause;
651  clause.append(d->relationField(tableName(), d->db.driver()->escapeIdentifier(rec.fieldName(i), QSqlDriver::FieldName)));
652  clause.append(QLatin1String(" = "));
653  clause.append(d->relationField(relTableAlias, relation.indexColumn()));
654 
655  tables.append(clause);
656  }
657  } else {
658  if (!fList.isEmpty())
659  fList.append(QLatin1String(", "));
660  fList.append(d->relationField(tableName(), d->db.driver()->escapeIdentifier(rec.fieldName(i), QSqlDriver::FieldName)));
661  }
662  }
663 
664  if (d->joinMode == QSqlRelationalTableModel::InnerJoin && !tables.isEmpty()) {
665  tList.append(tables.join(QLatin1String(", ")));
666  if(!tList.isEmpty())
667  tList.prepend(QLatin1String(", "));
668  } else
669  tList.append(tables.join(QLatin1String(" ")));
670 
671  if (fList.isEmpty())
672  return query;
673 
674  tList.prepend(tableName());
675  query.append(QLatin1String("SELECT "));
676  query.append(fList).append(QLatin1String(" FROM ")).append(tList);
677 
678  if (d->joinMode == QSqlRelationalTableModel::InnerJoin) {
679  qAppendWhereClause(query, where, filter());
680  } else if (!filter().isEmpty()) {
681  query.append(QLatin1String(" WHERE ("));
682  query.append(filter());
683  query.append(QLatin1String(")"));
684  }
685 
686  QString orderBy = orderByClause();
687  if (!orderBy.isEmpty())
688  query.append(QLatin1Char(' ')).append(orderBy);
689 
690  return query;
691 }
double d
Definition: qnumeric_p.h:62
QString section(QChar sep, int start, int end=-1, SectionFlags flags=SectionDefault) const
This function returns a section of the string.
Definition: qstring.h:781
The QSqlRelationalTableModel class provides an editable data model for a single database table...
virtual QString selectStatement() const
Returns the SQL SELECT statement used internally to populate the model.
QString tableName() const
Returns the name of the table to which a foreign key refers.
QString filter() const
Returns the currently set filter.
QSqlDatabase database() const
Returns a pointer to the used QSqlDatabase or 0 if no database was set.
QString & prepend(QChar c)
Definition: qstring.h:261
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
const T value(const Key &key) const
Returns the value associated with the key.
Definition: qhash.h:606
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
iterator insert(const Key &key, const T &value)
Inserts a new item with the key and a value of value.
Definition: qhash.h:753
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
QSqlRecord record(const QString &tablename) const
Returns a QSqlRecord populated with the names of all the fields in the table (or view) called tablena...
static bool isEmpty(const char *str)
QSqlQuery query() const
Returns the QSqlQuery associated with this model.
static void qAppendWhereClause(QString &query, const QString &clause1, const QString &clause2)
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
QString orderByClause() const
Reimplemented Function
const char * name
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal...
Definition: qstring.h:654
static QChar fromLatin1(char c)
Converts the Latin-1 character c to its equivalent QChar.
Definition: qchar.h:378
QSqlRelation relation(int column) const
Returns the relation for the column column, or an invalid relation if no relation is set...
The QSqlRelation class stores information about an SQL foreign key.
bool isValid() const
Returns true if the QSqlRelation object is valid; otherwise returns false.
QString join(const QString &sep) const
Joins all the string list&#39;s strings into a single string with each element separated by the given sep...
Definition: qstringlist.h:162
int count() const
Returns the number of fields in the record.
Definition: qsqlrecord.cpp:573
QString indexColumn() const
Returns the index column from table tableName() to which a foreign key refers.
QString arg(qlonglong a, int fieldwidth=0, int base=10, const QChar &fillChar=QLatin1Char(' ')) const Q_REQUIRED_RESULT
Definition: qstring.cpp:7186
QString & append(QChar c)
Definition: qstring.cpp:1777
int compare(const QString &s) const
Definition: qstring.cpp:5037
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
QString tableName() const
Returns the name of the currently selected table.
QString displayColumn() const
Returns the column from table tableName() that should be presented to the user instead of a foreign k...
QString fieldName(int i) const
Returns the name of the field at position index.
Definition: qsqlrecord.cpp:232
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ setData()

bool QSqlRelationalTableModel::setData ( const QModelIndex index,
const QVariant value,
int  role = Qt::EditRole 
)
virtual

Sets the data for the role in the item with the specified index to the value given.

Depending on the edit strategy, the value might be applied to the database at once, or it may be cached in the model.

Returns true if the value could be set, or false on error (for example, if index is out of bounds).

For relational columns, value must be the index, not the display value. The index must also exist in the referenced table, otherwise the function returns false.

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

Reimplemented from QAbstractItemModel.

Definition at line 503 of file qsqlrelationaltablemodel.cpp.

505 {
507  if ( role == Qt::EditRole && index.column() > 0 && index.column() < d->relations.count()
508  && d->relations.value(index.column()).isValid()) {
509  QRelation &relation = d->relations[index.column()];
510  if (!relation.isDictionaryInitialized())
511  relation.populateDictionary();
512  if (!relation.dictionary.contains(value.toString()))
513  return false;
514  }
515  return QSqlTableModel::setData(index, value, role);
516 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
QString toString() const
Returns the variant as a QString if the variant has type() String , Bool , ByteArray ...
Definition: qvariant.cpp:2270
#define Q_D(Class)
Definition: qglobal.h:2482
bool contains(const Key &key) const
Returns true if the hash contains an item with the key; otherwise returns false.
Definition: qhash.h:872
QSqlRelation relation(int column) const
Returns the relation for the column column, or an invalid relation if no relation is set...
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.
QHash< QString, QVariant > dictionary
int column() const
Returns the column this model index refers to.

◆ setJoinMode()

void QSqlRelationalTableModel::setJoinMode ( QSqlRelationalTableModel::JoinMode  joinMode)

Sets the SQL join mode to the value given by joinMode to show or hide rows with NULL foreign keys.

Since
4.8

In InnerJoin mode (the default) these rows will not be shown; use the LeftJoin mode if you want to show them.

See also
QSqlRelationalTableModel::JoinMode

Definition at line 768 of file qsqlrelationaltablemodel.cpp.

769 {
771  d->joinMode = joinMode;
772 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
#define Q_D(Class)
Definition: qglobal.h:2482

◆ setRelation()

void QSqlRelationalTableModel::setRelation ( int  column,
const QSqlRelation relation 
)
virtual

Lets the specified column be a foreign index specified by relation.

Example:

model->setTable("employee");
model->setRelation(2, QSqlRelation("city", "id", "name"));

The setRelation() call specifies that column 2 in table employee is a foreign key that maps with field id of table city, and that the view should present the city's name field to the user.

Note: The table's primary key may not contain a relation to another table.

See also
relation()

Definition at line 536 of file qsqlrelationaltablemodel.cpp.

537 {
539  if (column < 0)
540  return;
541  if (d->relations.size() <= column)
542  d->relations.resize(column + 1);
543  d->relations[column].init(this, relation);
544 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
#define Q_D(Class)
Definition: qglobal.h:2482

◆ setTable()

void QSqlRelationalTableModel::setTable ( const QString tableName)
virtual

Reimplemented Function

Reimplemented from QSqlTableModel.

Definition at line 784 of file qsqlrelationaltablemodel.cpp.

785 {
787 
788  // memorize the table before applying the relations
789  d->baseRec = d->db.record(table);
790 
792 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
#define Q_D(Class)
Definition: qglobal.h:2482
virtual void setTable(const QString &tableName)
Sets the database table on which the model operates to tableName.

◆ updateRowInTable()

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

Reimplemented Function

Reimplemented from QSqlTableModel.

Definition at line 815 of file qsqlrelationaltablemodel.cpp.

816 {
818 
819  QSqlRecord rec = values;
820  d->translateFieldNames(row, rec);
821 
822  return QSqlTableModel::updateRowInTable(row, rec);
823 }
double d
Definition: qnumeric_p.h:62
The QSqlRelationalTableModel class provides an editable data model for a single database table...
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
#define Q_D(Class)
Definition: qglobal.h:2482
virtual bool updateRowInTable(int row, const QSqlRecord &values)
Updates the given row in the currently active database table with the specified values.
quint16 values[128]

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