Qt 4.8
Public Functions | Protected Functions | List of all members
QSqlQueryModel Class Reference

The QSqlQueryModel class provides a read-only data model for SQL result sets. More...

#include <qsqlquerymodel.h>

Inheritance diagram for QSqlQueryModel:
QAbstractTableModel QAbstractItemModel QObject QSqlTableModel QRelatedTableModel QSqlRelationalTableModel

Public Functions

bool canFetchMore (const QModelIndex &parent=QModelIndex()) const
 Returns true if it is possible to read more rows from the database. More...
 
virtual void clear ()
 Clears the model and releases any acquired resource. More...
 
int columnCount (const QModelIndex &parent=QModelIndex()) const
 Reimplemented Function More...
 
QVariant data (const QModelIndex &item, int role=Qt::DisplayRole) const
 Returns the value for the specified item and role. More...
 
void fetchMore (const QModelIndex &parent=QModelIndex())
 Fetches more rows from a database. More...
 
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 orientation. 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 removeColumns (int column, int count, const QModelIndex &parent=QModelIndex())
 Removes count columns from the model starting from position column. More...
 
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. 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...
 
virtual Qt::ItemFlags flags (const QModelIndex &index) const
 Returns the item flags for the given 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 bool insertRows (int row, int count, const QModelIndex &parent=QModelIndex())
 On models that support this, inserts count rows into the model before the given row. 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...
 
virtual bool removeRows (int row, int count, const QModelIndex &parent=QModelIndex())
 On models that support this, removes count rows starting with the given row under parent parent from the model. More...
 
const QHash< int, QByteArray > & roleNames () const
 Returns the model's role names. More...
 
virtual bool setData (const QModelIndex &index, const QVariant &value, int role=Qt::EditRole)
 Sets the role data for the item at index to value. 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 void sort (int column, Qt::SortOrder order=Qt::AscendingOrder)
 Sorts the model by column in the given order. 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

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

- 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 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 QSqlQueryModel class provides a read-only data model for SQL result sets.

Attention
Module: QtSql

QSqlQueryModel is a high-level interface for executing SQL statements and traversing the result set. It is built on top of the lower-level QSqlQuery and can be used to provide data to view classes such as QTableView. For example:

model->setQuery("SELECT name, salary FROM employee");
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
QTableView *view = new QTableView;
view->setModel(model);
view->show();

We set the model's query, then we set up the labels displayed in the view header.

QSqlQueryModel 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. Assuming that salary is column 2, we can rewrite the last line as follows:

int salary = model.data(model.index(4, 2)).toInt();

The model is read-only by default. To make it read-write, you must subclass it and reimplement setData() and flags(). Another option is to use QSqlTableModel, which provides a read-write model based on a single database table.

The sql/querymodel example illustrates how to use QSqlQueryModel to display the result of a query. It also shows how to subclass QSqlQueryModel to customize the contents of the data before showing it to the user, and how to create a read-write model based on QSqlQueryModel.

If the database doesn't return the number of selected rows in a query, the model will fetch rows incrementally. See fetchMore() for more information.

See also
QSqlTableModel, QSqlRelationalTableModel, QSqlQuery, {Model/View Programming}, {Query Model Example}

Definition at line 59 of file qsqlquerymodel.h.

Constructors and Destructors

◆ QSqlQueryModel() [1/2]

QSqlQueryModel::QSqlQueryModel ( QObject parent = 0)
explicit

Creates an empty QSqlQueryModel with the given parent.

Definition at line 153 of file qsqlquerymodel.cpp.

155 {
156 }
QAbstractTableModel(QObject *parent=0)
Constructs an abstract table model for the given parent.

◆ ~QSqlQueryModel()

QSqlQueryModel::~QSqlQueryModel ( )
virtual

Destroys the object and frees any allocated resources.

See also
clear()

Definition at line 170 of file qsqlquerymodel.cpp.

171 {
172 }

◆ QSqlQueryModel() [2/2]

QSqlQueryModel::QSqlQueryModel ( QSqlQueryModelPrivate dd,
QObject parent = 0 
)
protected
Warning
This function is not part of the public interface.

Definition at line 160 of file qsqlquerymodel.cpp.

161  : QAbstractTableModel(dd, parent)
162 {
163 }
QAbstractTableModel(QObject *parent=0)
Constructs an abstract table model for the given parent.

Functions

◆ canFetchMore()

bool QSqlQueryModel::canFetchMore ( const QModelIndex parent = QModelIndex()) const
virtual

Returns true if it is possible to read more rows from the database.

Since
4.1

This only affects databases that don't report back the size of a query (see QSqlDriver::hasFeature()).

parent should always be an invalid QModelIndex.

See also
fetchMore()

Reimplemented from QAbstractItemModel.

Definition at line 214 of file qsqlquerymodel.cpp.

215 {
216  Q_D(const QSqlQueryModel);
217  return (!parent.isValid() && !d->atEnd);
218 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.
bool isValid() const
Returns true if this model index is valid; otherwise returns false.

◆ clear()

void QSqlQueryModel::clear ( void  )
virtual

Clears the model and releases any acquired resource.

Reimplemented in QSqlRelationalTableModel, and QSqlTableModel.

Definition at line 413 of file qsqlquerymodel.cpp.

Referenced by QSqlTableModel::clear().

414 {
416  d->error = QSqlError();
417  d->atEnd = true;
418  d->query.clear();
419  d->rec.clear();
420  d->colOffsets.clear();
421  d->bottom = QModelIndex();
422  d->headers.clear();
423 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.
The QModelIndex class is used to locate data in a data model.

◆ columnCount()

int QSqlQueryModel::columnCount ( const QModelIndex parent = QModelIndex()) const
virtual

Reimplemented Function

Implements QAbstractItemModel.

Definition at line 243 of file qsqlquerymodel.cpp.

Referenced by QSqlTableModel::revertRow(), setHeaderData(), and QSqlTableModel::setRecord().

244 {
245  Q_D(const QSqlQueryModel);
246  return index.isValid() ? 0 : d->rec.count();
247 }
double d
Definition: qnumeric_p.h:62
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const
Returns the index of the data in row and column with parent.
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.
bool isValid() const
Returns true if this model index is valid; otherwise returns false.

◆ data()

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

Returns the value for the specified item and role.

If item is out of bounds or if an error occurred, an invalid QVariant is returned.

See also
lastError()

Implements QAbstractItemModel.

Reimplemented in QSqlRelationalTableModel, and QSqlTableModel.

Definition at line 257 of file qsqlquerymodel.cpp.

Referenced by QSqlTableModel::data(), and record().

258 {
259  Q_D(const QSqlQueryModel);
260  if (!item.isValid())
261  return QVariant();
262 
263  QVariant v;
264  if (role & ~(Qt::DisplayRole | Qt::EditRole))
265  return v;
266 
267  if (!d->rec.isGenerated(item.column()))
268  return v;
269  QModelIndex dItem = indexInQuery(item);
270  if (dItem.row() > d->bottom.row())
271  const_cast<QSqlQueryModelPrivate *>(d)->prefetch(dItem.row());
272 
273  if (!d->query.seek(dItem.row())) {
274  d->error = d->query.lastError();
275  return v;
276  }
277 
278  return d->query.value(dItem.column());
279 }
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
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
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.
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.
int column() const
Returns the column this model index refers to.

◆ fetchMore()

void QSqlQueryModel::fetchMore ( const QModelIndex parent = QModelIndex())
virtual

Fetches more rows from a database.

Since
4.1

This only affects databases that don't report back the size of a query (see QSqlDriver::hasFeature()).

To force fetching of the entire result set, you can use the following:

while (myModel->canFetchMore())
myModel->fetchMore();

parent should always be an invalid QModelIndex.

See also
canFetchMore()

Reimplemented from QAbstractItemModel.

Definition at line 192 of file qsqlquerymodel.cpp.

Referenced by setQuery().

193 {
195  if (parent.isValid())
196  return;
197  d->prefetch(qMax(d->bottom.row(), 0) + QSQL_PREFETCH);
198 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
#define QSQL_PREFETCH
The QSqlQueryModel class provides a read-only data model for SQL result sets.
bool isValid() const
Returns true if this model index is valid; otherwise returns false.

◆ headerData()

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

Returns the header data for the given role in the section of the header with the specified orientation.

Reimplemented from QAbstractItemModel.

Reimplemented in QSqlTableModel.

Definition at line 285 of file qsqlquerymodel.cpp.

Referenced by QSqlTableModel::headerData().

286 {
287  Q_D(const QSqlQueryModel);
288  if (orientation == Qt::Horizontal) {
289  QVariant val = d->headers.value(section).value(role);
290  if (role == Qt::DisplayRole && !val.isValid())
291  val = d->headers.value(section).value(Qt::EditRole);
292  if (val.isValid())
293  return val;
294 
295  // See if it's an inserted column (iiq.column() != -1)
296  QModelIndex dItem = indexInQuery(createIndex(0, section));
297 
298  if (role == Qt::DisplayRole && d->rec.count() > section && dItem.column() != -1)
299  return d->rec.fieldName(section);
300  }
301  return QAbstractItemModel::headerData(section, orientation, role);
302 }
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
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
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
virtual QVariant headerData(int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const
Returns the data for the given role and section in the header with the specified orientation.
The QSqlQueryModel class provides a read-only data model for SQL result sets.
The QModelIndex class is used to locate data in a data model.
bool isValid() const
Returns true if the storage type of this variant is not QVariant::Invalid; otherwise returns false...
Definition: qvariant.h:485
int column() const
Returns the column this model index refers to.

◆ indexInQuery()

QModelIndex QSqlQueryModel::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
QSqlTableModel::indexInQuery(), insertColumns(), removeColumns()

Definition at line 608 of file qsqlquerymodel.cpp.

Referenced by data(), headerData(), and QSqlTableModel::indexInQuery().

609 {
610  Q_D(const QSqlQueryModel);
611  if (item.column() < 0 || item.column() >= d->rec.count()
612  || !d->rec.isGenerated(item.column()))
613  return QModelIndex();
614  return createIndex(item.row(), item.column() - d->colOffsets[item.column()],
615  item.internalPointer());
616 }
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...
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
The QSqlQueryModel class provides a read-only data model for SQL result sets.
int row() const
Returns the row this model index refers to.
The QModelIndex class is used to locate data in a data model.
int column() const
Returns the column this model index refers to.

◆ insertColumns()

bool QSqlQueryModel::insertColumns ( int  column,
int  count,
const QModelIndex parent = QModelIndex() 
)
virtual

Inserts count columns into the model at position column.

The parent parameter must always be an invalid QModelIndex, since the model does not support parent-child relationships.

Returns true if column is within bounds; otherwise returns false.

By default, inserted columns are empty. To fill them with data, reimplement data() and handle any inserted column separately:

QVariant MyModel::data(const QModelIndex &item, int role) const
{
if (item.column() == m_specialColumnNo) {
// handle column separately
}
return QSqlQueryModel::data(item, role);
}
See also
removeColumns()

Reimplemented from QAbstractItemModel.

Definition at line 543 of file qsqlquerymodel.cpp.

544 {
546  if (count <= 0 || parent.isValid() || column < 0 || column > d->rec.count())
547  return false;
548 
549  beginInsertColumns(parent, column, column + count - 1);
550  for (int c = 0; c < count; ++c) {
551  QSqlField field;
552  field.setReadOnly(true);
553  field.setGenerated(false);
554  d->rec.insert(column, field);
555  if (d->colOffsets.size() < d->rec.count()) {
556  int nVal = d->colOffsets.isEmpty() ? 0 : d->colOffsets[d->colOffsets.size() - 1];
557  d->colOffsets.append(nVal);
558  Q_ASSERT(d->colOffsets.size() >= d->rec.count());
559  }
560  for (int i = column + 1; i < d->colOffsets.count(); ++i)
561  ++d->colOffsets[i];
562  }
564  return true;
565 }
double d
Definition: qnumeric_p.h:62
unsigned char c[8]
Definition: qnumeric_p.h:62
void beginInsertColumns(const QModelIndex &parent, int first, int last)
Begins a column insertion operation.
void setReadOnly(bool readOnly)
Sets the read only flag of the field&#39;s value to readOnly.
Definition: qsqlfield.cpp:358
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
#define Q_D(Class)
Definition: qglobal.h:2482
void setGenerated(bool gen)
Sets the generated state.
Definition: qsqlfield.cpp:299
The QSqlQueryModel class provides a read-only data model for SQL result sets.
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
void endInsertColumns()
Ends a column insertion operation.
The QSqlField class manipulates the fields in SQL database tables and views.
Definition: qsqlfield.h:56

◆ lastError()

QSqlError QSqlQueryModel::lastError ( ) const

Returns information about the last error that occurred on the database.

See also
query()

Definition at line 470 of file qsqlquerymodel.cpp.

Referenced by QSqlTableModel::select().

471 {
472  Q_D(const QSqlQueryModel);
473  return d->error;
474 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.

◆ query()

QSqlQuery QSqlQueryModel::query ( ) const

Returns the QSqlQuery associated with this model.

See also
setQuery()

Definition at line 458 of file qsqlquerymodel.cpp.

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

459 {
460  Q_D(const QSqlQueryModel);
461  return d->query;
462 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.

◆ queryChange()

void QSqlQueryModel::queryChange ( )
protectedvirtual

This virtual function is called whenever the query changes.

The default implementation does nothing.

query() returns the new query.

See also
query(), setQuery()

Definition at line 312 of file qsqlquerymodel.cpp.

Referenced by setQuery().

313 {
314  // do nothing
315 }

◆ record() [1/2]

QSqlRecord QSqlQueryModel::record ( int  row) const

Returns the record containing information about the fields of the current query.

If row is the index of a valid row, the record will be populated with values from that row.

If the model is not initialized, an empty record will be returned.

See also
QSqlRecord::isEmpty()

Definition at line 498 of file qsqlquerymodel.cpp.

Referenced by QRelation::populateDictionary().

499 {
500  Q_D(const QSqlQueryModel);
501  if (row < 0)
502  return d->rec;
503 
504  QSqlRecord rec = d->rec;
505  for (int i = 0; i < rec.count(); ++i)
506  rec.setValue(i, data(createIndex(row, i), Qt::EditRole));
507  return rec;
508 }
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. ...
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
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
The QSqlQueryModel class provides a read-only data model for SQL result sets.
int count() const
Returns the number of fields in the record.
Definition: qsqlrecord.cpp:573
void setValue(int i, const QVariant &val)
Sets the value of the field at position index to val.
Definition: qsqlrecord.cpp:585

◆ record() [2/2]

QSqlRecord QSqlQueryModel::record ( ) const

Returns an empty record containing information about the fields of the current query.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

If the model is not initialized, an empty record will be returned.

See also
QSqlRecord::isEmpty()

Definition at line 523 of file qsqlquerymodel.cpp.

524 {
525  Q_D(const QSqlQueryModel);
526  return d->rec;
527 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.

◆ removeColumns()

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

Removes count columns from the model starting from position column.

The parent parameter must always be an invalid QModelIndex, since the model does not support parent-child relationships.

Removing columns effectively hides them. It does not affect the underlying QSqlQuery.

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

Reimplemented from QAbstractItemModel.

Reimplemented in QSqlTableModel, and QSqlRelationalTableModel.

Definition at line 578 of file qsqlquerymodel.cpp.

579 {
581  if (count <= 0 || parent.isValid() || column < 0 || column >= d->rec.count())
582  return false;
583 
584  beginRemoveColumns(parent, column, column + count - 1);
585 
586  int i;
587  for (i = 0; i < count; ++i)
588  d->rec.remove(column);
589  for (i = column; i < d->colOffsets.count(); ++i)
590  d->colOffsets[i] -= count;
591 
593  return true;
594 }
double d
Definition: qnumeric_p.h:62
void beginRemoveColumns(const QModelIndex &parent, int first, int last)
Begins a column removal operation.
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.
bool isValid() const
Returns true if this model index is valid; otherwise returns false.
void endRemoveColumns()
Ends a column removal operation.

◆ rowCount()

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

If the database supports returning the size of a query (see QSqlDriver::hasFeature()), the number of rows of the current query is returned.

Since
4.1

Otherwise, returns the number of rows currently cached on the client.

parent should always be an invalid QModelIndex.

See also
canFetchMore(), QSqlDriver::hasFeature()

Implements QAbstractItemModel.

Reimplemented in QSqlTableModel.

Definition at line 235 of file qsqlquerymodel.cpp.

Referenced by QSqlTableModel::rowCount().

236 {
237  Q_D(const QSqlQueryModel);
238  return index.isValid() ? 0 : d->bottom.row() + 1;
239 }
double d
Definition: qnumeric_p.h:62
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const
Returns the index of the data in row and column with parent.
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.
bool isValid() const
Returns true if this model index is valid; otherwise returns false.

◆ setHeaderData()

bool QSqlQueryModel::setHeaderData ( int  section,
Qt::Orientation  orientation,
const QVariant value,
int  role = Qt::EditRole 
)
virtual

Sets the caption for a horizontal header for the specified role to value.

This is useful if the model is used to display data in a view (e.g., QTableView).

Returns true if orientation is Qt::Horizontal and the section refers to a valid section; otherwise returns false.

Note that this function cannot be used to modify values in the database since the model is read-only.

See also
data()

Reimplemented from QAbstractItemModel.

Definition at line 439 of file qsqlquerymodel.cpp.

441 {
443  if (orientation != Qt::Horizontal || section < 0 || columnCount() <= section)
444  return false;
445 
446  if (d->headers.size() <= section)
447  d->headers.resize(qMax(section + 1, 16));
448  d->headers[section][role] = value;
449  emit headerDataChanged(orientation, section, section);
450  return true;
451 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
int columnCount(const QModelIndex &parent=QModelIndex()) const
Reimplemented Function
The QSqlQueryModel class provides a read-only data model for SQL result sets.
#define emit
Definition: qobjectdefs.h:76
void headerDataChanged(Qt::Orientation orientation, int first, int last)
This signal is emitted whenever a header is changed.

◆ setLastError()

void QSqlQueryModel::setLastError ( const QSqlError error)
protected

Protected function which allows derived classes to set the value of the last error that occurred on the database to error.

See also
lastError()

Definition at line 482 of file qsqlquerymodel.cpp.

483 {
485  d->error = error;
486 }
double d
Definition: qnumeric_p.h:62
#define error(msg)
#define Q_D(Class)
Definition: qglobal.h:2482
The QSqlQueryModel class provides a read-only data model for SQL result sets.

◆ setQuery() [1/2]

void QSqlQueryModel::setQuery ( const QSqlQuery query)

Resets the model and sets the data provider to be the given query.

Note that the query must be active and must not be isForwardOnly().

lastError() can be used to retrieve verbose information if there was an error setting the query.

Note
Calling setQuery() will remove any inserted columns.
See also
query(), QSqlQuery::isActive(), QSqlQuery::setForwardOnly(), lastError()

Definition at line 329 of file qsqlquerymodel.cpp.

Referenced by setQuery(), and QSqlTableModel::setQuery().

330 {
332  QSqlRecord newRec = query.record();
333  bool columnsChanged = (newRec != d->rec);
334  bool hasQuerySize = query.driver()->hasFeature(QSqlDriver::QuerySize);
335  bool hasNewData = (newRec != QSqlRecord()) || !query.lastError().isValid();
336 
337  if (d->colOffsets.size() != newRec.count() || columnsChanged)
338  d->initColOffsets(newRec.count());
339 
340  bool mustClearModel = d->bottom.isValid();
341  if (mustClearModel) {
342  d->atEnd = true;
343  beginRemoveRows(QModelIndex(), 0, qMax(d->bottom.row(), 0));
344  d->bottom = QModelIndex();
345  }
346 
347  d->error = QSqlError();
348  d->query = query;
349  d->rec = newRec;
350 
351  if (mustClearModel)
352  endRemoveRows();
353 
354  d->atEnd = false;
355 
356  if (columnsChanged && hasNewData)
357  reset();
358 
359  if (!query.isActive() || query.isForwardOnly()) {
360  d->atEnd = true;
361  d->bottom = QModelIndex();
362  if (query.isForwardOnly())
363  d->error = QSqlError(QLatin1String("Forward-only queries "
364  "cannot be used in a data model"),
366  else
367  d->error = query.lastError();
368  return;
369  }
370  QModelIndex newBottom;
371  if (hasQuerySize && d->query.size() > 0) {
372  newBottom = createIndex(d->query.size() - 1, d->rec.count() - 1);
373  beginInsertRows(QModelIndex(), 0, qMax(0, newBottom.row()));
374  d->bottom = createIndex(d->query.size() - 1, columnsChanged ? 0 : d->rec.count() - 1);
375  d->atEnd = true;
376  endInsertRows();
377  } else {
378  newBottom = createIndex(-1, d->rec.count() - 1);
379  }
380  d->bottom = newBottom;
381 
382  queryChange();
383 
384  // fetchMore does the rowsInserted stuff for incremental models
385  fetchMore();
386 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
double d
Definition: qnumeric_p.h:62
const QSqlDriver * driver() const
Returns the database driver associated with the query.
Definition: qsqlquery.cpp:441
virtual bool hasFeature(DriverFeature f) const =0
Returns true if the driver supports feature feature; otherwise returns false.
QSqlRecord record() const
Returns a QSqlRecord containing the field information for the current query.
Definition: qsqlquery.cpp:858
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. ...
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
void endInsertRows()
Ends a row insertion operation.
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
#define Q_D(Class)
Definition: qglobal.h:2482
virtual void queryChange()
This virtual function is called whenever the query changes.
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
The QSqlQueryModel class provides a read-only data model for SQL result sets.
QSqlQuery query() const
Returns the QSqlQuery associated with this model.
int row() const
Returns the row this model index refers to.
void endRemoveRows()
Ends a row removal operation.
int count() const
Returns the number of fields in the record.
Definition: qsqlrecord.cpp:573
QSqlError lastError() const
Returns error information about the last error (if any) that occurred with this query.
Definition: qsqlquery.cpp:754
void beginRemoveRows(const QModelIndex &parent, int first, int last)
Begins a row removal operation.
The QModelIndex class is used to locate data in a data model.
bool isForwardOnly() const
Returns true if you can only scroll forward through a result set; otherwise returns false...
Definition: qsqlquery.cpp:806
bool isValid() const
Returns true if an error is set, otherwise false.
Definition: qsqlerror.cpp:254
void fetchMore(const QModelIndex &parent=QModelIndex())
Fetches more rows from a database.
void reset()
Resets the model to its original state in any attached views.
void beginInsertRows(const QModelIndex &parent, int first, int last)
Begins a row insertion operation.

◆ setQuery() [2/2]

void QSqlQueryModel::setQuery ( const QString query,
const QSqlDatabase db = QSqlDatabase() 
)

Executes the query query for the given database connection db.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

If no database (or an invalid database) is specified, the default connection is used.

lastError() can be used to retrieve verbose information if there was an error setting the query.

Example:

model.setQuery("select * from MyTable");
if (model.lastError().isValid())
qDebug() << model.lastError();
See also
query(), queryChange(), lastError()

Definition at line 405 of file qsqlquerymodel.cpp.

406 {
407  setQuery(QSqlQuery(query, db));
408 }
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition: qsqlquery.h:63
void setQuery(const QSqlQuery &query)
Resets the model and sets the data provider to be the given query.

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