CopperSpice API  1.7.2
QSqlQueryModel Class Reference

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

Inheritance diagram for QSqlQueryModel:
QAbstractTableModel QAbstractItemModel QObject QSqlTableModel QSqlRelationalTableModel

Public Methods

 QSqlQueryModel (QObject *parent=nullptr)
 
virtual ~QSqlQueryModel ()
 
bool canFetchMore (const QModelIndex &parent=QModelIndex ()) const override
 
virtual void clear ()
 
int columnCount (const QModelIndex &index=QModelIndex ()) const override
 
QVariant data (const QModelIndex &item, int role=Qt::DisplayRole) const override
 
void fetchMore (const QModelIndex &parent=QModelIndex ()) override
 
QVariant headerData (int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const override
 
bool insertColumns (int column, int count, const QModelIndex &parent=QModelIndex ()) override
 
QSqlError lastError () const
 
QSqlQuery query () const
 
QSqlRecord record () const
 
QSqlRecord record (int row) const
 
bool removeColumns (int column, int count, const QModelIndex &parent=QModelIndex ()) override
 
int rowCount (const QModelIndex &index=QModelIndex ()) const override
 
bool setHeaderData (int section, Qt::Orientation orientation, const QVariant &value, int role=Qt::EditRole) override
 
void setQuery (const QSqlQuery &query)
 
void setQuery (const QString &query, const QSqlDatabase &db=QSqlDatabase ())
 
- Public Methods inherited from QAbstractTableModel
 QAbstractTableModel (QObject *parent=nullptr)
 
 ~QAbstractTableModel ()
 
bool dropMimeData (const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override
 
Qt::ItemFlags flags (const QModelIndex &index) const override
 
QModelIndex index (int row, int column, const QModelIndex &parent=QModelIndex ()) const override
 
QObjectparent () const
 
QModelIndex sibling (int row, int column, const QModelIndex &index) const override
 
- Public Methods inherited from QAbstractItemModel
 QAbstractItemModel (QObject *parent=nullptr)
 
virtual ~QAbstractItemModel ()
 
virtual QModelIndex buddy (const QModelIndex &index) const
 
virtual bool canDropMimeData (const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
 
bool hasIndex (int row, int column, const QModelIndex &parent=QModelIndex ()) const
 
bool insertColumn (int column, const QModelIndex &parent=QModelIndex ())
 
bool insertRow (int row, const QModelIndex &parent=QModelIndex ())
 
virtual bool insertRows (int row, int count, const QModelIndex &parent=QModelIndex ())
 
virtual QMap< int, QVariantitemData (const QModelIndex &index) const
 
virtual QModelIndexList match (const QModelIndex &start, int role, const QVariant &value, int hits=1, Qt::MatchFlags flags=Qt::MatchFlags (Qt::MatchStartsWith|Qt::MatchWrap)) const
 
virtual QMimeDatamimeData (const QModelIndexList &indexes) const
 
virtual QStringList mimeTypes () const
 
bool moveColumn (const QModelIndex &sourceParent, int sourceColumn, const QModelIndex &destinationParent, int destinationChild)
 
virtual bool moveColumns (const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destinationParent, int destinationChild)
 
bool moveRow (const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild)
 
virtual bool moveRows (const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild)
 
QObjectparent () const
 
bool removeColumn (int column, const QModelIndex &parent=QModelIndex ())
 
bool removeRow (int row, const QModelIndex &parent=QModelIndex ())
 
virtual bool removeRows (int row, int count, const QModelIndex &parent=QModelIndex ())
 
virtual QMultiHash< int, QStringroleNames () const
 
virtual bool setData (const QModelIndex &index, const QVariant &value, int role=Qt::EditRole)
 
virtual bool setItemData (const QModelIndex &index, const QMap< int, QVariant > &roles)
 
virtual void sort (int column, Qt::SortOrder order=Qt::AscendingOrder)
 
virtual QSize span (const QModelIndex &index) const
 
virtual Qt::DropActions supportedDragActions () const
 
virtual Qt::DropActions supportedDropActions () const
 
- Public Methods inherited from QObject
 QObject (QObject *parent=nullptr)
 
 ~QObject ()
 
bool blockSignals (bool block)
 
const QList< QObject * > & children () const
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool disconnect (const QObject *receiver, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod, const QString &location, const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod=QString (), const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
void dumpObjectInfo ()
 
void dumpObjectTree ()
 
QList< QStringdynamicPropertyNames () const
 
virtual bool event (QEvent *event)
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 
template<typename T >
findChild (const QString &childName=QString ()) const
 
template<class T >
QList< T > findChildren (const QRegularExpression &regExp, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
template<class T >
QList< T > findChildren (const QString &objName=QString (), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
bool inherits (const QString &className) const
 
void installEventFilter (QObject *filterObj)
 
bool isWidgetType () const
 
bool isWindowType () const
 
void killTimer (int id)
 
const QMetaObjectmetaObject () const
 
void moveToThread (QThread *targetThread)
 
QString objectName () const
 
QObject * parent () const
 
template<class T = QVariant>
property (const QString &name) const
 
void removeEventFilter (QObject *obj)
 
void setObjectName (const QString &name)
 
void setParent (QObject *parent)
 
bool setProperty (const QString &name, const QVariant &value)
 
bool signalsBlocked () const
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 
QThreadthread () const
 

Protected Methods

virtual QModelIndex indexInQuery (const QModelIndex &item) const
 
virtual void queryChange ()
 
void setLastError (const QSqlError &error)
 
- Protected Methods inherited from QAbstractItemModel
void beginInsertColumns (const QModelIndex &parent, int first, int last)
 
void beginInsertRows (const QModelIndex &parent, int first, int last)
 
bool beginMoveColumns (const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationColumn)
 
bool beginMoveRows (const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationRow)
 
void beginRemoveColumns (const QModelIndex &parent, int first, int last)
 
void beginRemoveRows (const QModelIndex &parent, int first, int last)
 
void beginResetModel ()
 
void changePersistentIndex (const QModelIndex &from, const QModelIndex &to)
 
void changePersistentIndexList (const QModelIndexList &from, const QModelIndexList &to)
 
QModelIndex createIndex (int row, int column, quintptr id) const
 
QModelIndex createIndex (int row, int column, void *data=nullptr) const
 
void endInsertColumns ()
 
void endInsertRows ()
 
void endMoveColumns ()
 
void endMoveRows ()
 
void endRemoveColumns ()
 
void endRemoveRows ()
 
void endResetModel ()
 
QModelIndexList persistentIndexList () const
 
- Protected Methods inherited from QObject
virtual void childEvent (QChildEvent *event)
 
virtual void connectNotify (const QMetaMethod &signalMethod) const
 
virtual void customEvent (QEvent *event)
 
virtual void disconnectNotify (const QMetaMethod &signalMethod) const
 
bool isSignalConnected (const QMetaMethod &signalMethod) const
 
int receivers (const QString &signal) const
 
QObject * sender () const
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *event)
 

Additional Inherited Members

- Public Signals inherited from QAbstractItemModel
void columnsAboutToBeInserted (const QModelIndex &parent, int first, int last)
 
void columnsAboutToBeMoved (const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationColumn)
 
void columnsAboutToBeRemoved (const QModelIndex &parent, int first, int last)
 
void columnsInserted (const QModelIndex &parent, int first, int last)
 
void columnsMoved (const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationColumn)
 
void columnsRemoved (const QModelIndex &parent, int first, int last)
 
void dataChanged (const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector< int > &roles=QVector< int >())
 
void headerDataChanged (Qt::Orientation orientation, int first, int last)
 
void layoutAboutToBeChanged (const QList< QPersistentModelIndex > &parents=QList< QPersistentModelIndex >(), QAbstractItemModel::LayoutChangeHint hint=QAbstractItemModel::NoLayoutChangeHint)
 
void layoutChanged (const QList< QPersistentModelIndex > &parents=QList< QPersistentModelIndex >(), QAbstractItemModel::LayoutChangeHint hint=QAbstractItemModel::NoLayoutChangeHint)
 
void modelAboutToBeReset ()
 
void modelReset ()
 
void rowsAboutToBeInserted (const QModelIndex &parent, int first, int last)
 
void rowsAboutToBeMoved (const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)
 
void rowsAboutToBeRemoved (const QModelIndex &parent, int first, int last)
 
void rowsInserted (const QModelIndex &parent, int first, int last)
 
void rowsMoved (const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)
 
void rowsRemoved (const QModelIndex &parent, int first, int last)
 
- Public Signals inherited from QObject
void destroyed (QObject *obj=nullptr)
 
void objectNameChanged (const QString &objectName)
 
- Public Slots inherited from QAbstractItemModel
virtual void revert ()
 
virtual bool submit ()
 
- Public Slots inherited from QObject
void deleteLater ()
 
- Static Public Methods inherited from QObject
static bool connect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool connect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection, const QString &location=QString ())
 
static bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...), Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotLambda, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...))
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, std::nullptr_t slotMethod=nullptr)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotMethod)
 
static QMetaObjectstaticMetaObject ()
 
static QString tr (const char *text, const char *comment=nullptr, std::optional< int > numArg=std::optional< int >())
 
- Protected Slots inherited from QAbstractItemModel
void resetInternalData ()
 
- Properties inherited from QObject
 objectName
 

Detailed Description

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

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.

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.

If the database does not 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

Constructor & Destructor Documentation

QSqlQueryModel::QSqlQueryModel ( QObject parent = nullptr)
explicit

Creates an empty QSqlQueryModel with the given parent.

QSqlQueryModel::~QSqlQueryModel ( )
virtual

Destroys the object and frees any allocated resources.

See also
clear()

Method Documentation

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

Returns true if it is possible to read more rows from the database. This only affects databases that do not report back the size of a query (see QSqlDriver::hasFeature()).

parent should always be an invalid QModelIndex.

See also
fetchMore()

Reimplemented from QAbstractItemModel.

void QSqlQueryModel::clear ( )
virtual

Clears the model and releases any acquired resource.

Reimplemented in QSqlRelationalTableModel, and QSqlTableModel.

int QSqlQueryModel::columnCount ( const QModelIndex index = QModelIndex()) const
overridevirtual

Reimplemented from QAbstractItemModel::columnCount().

Implements QAbstractItemModel.

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

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.

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

Fetches more rows from a database. This only affects databases that do not 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.

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

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

See also
setHeaderData()

Reimplemented from QAbstractItemModel.

Reimplemented in QSqlTableModel.

QModelIndex QSqlQueryModel::indexInQuery ( const QModelIndex item) const
protectedvirtual

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

Reimplemented in QSqlTableModel.

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

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.

QSqlError QSqlQueryModel::lastError ( ) const

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

See also
setLastError(), query()
QSqlQuery QSqlQueryModel::query ( ) const

Returns the QSqlQuery associated with this model.

See also
setQuery()
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()
QSqlRecord QSqlQueryModel::record ( ) const

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

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

See also
QSqlRecord::isEmpty()
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()
bool QSqlQueryModel::removeColumns ( int  column,
int  count,
const QModelIndex parent = QModelIndex() 
)
overridevirtual

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.

int QSqlQueryModel::rowCount ( const QModelIndex index = QModelIndex()) const
overridevirtual

If the database supports returning the size of a query the number of rows of the current query is returned. Otherwise, returns the number of rows currently cached on the client. The index should always be an invalid QModelIndex.

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

Implements QAbstractItemModel.

Reimplemented in QSqlTableModel.

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

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 can not be used to modify values in the database since the model is read-only.

See also
headerData(), data()

Reimplemented from QAbstractItemModel.

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()
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()
void QSqlQueryModel::setQuery ( const QString query,
const QSqlDatabase db = QSqlDatabase() 
)

Executes the query query for the given database connection db. 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()