Qt Jambi Home

com.trolltech.qt.sql
Class QSqlQueryModel

java.lang.Object
  extended by com.trolltech.qt.QSignalEmitter
      extended by com.trolltech.qt.QtJambiObject
          extended by com.trolltech.qt.core.QObject
              extended by com.trolltech.qt.core.QAbstractItemModel
                  extended by com.trolltech.qt.gui.QAbstractTableModel
                      extended by com.trolltech.qt.sql.QSqlQueryModel
All Implemented Interfaces:
QtJambiInterface
Direct Known Subclasses:
QSqlTableModel

public class QSqlQueryModel
extends QAbstractTableModel

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. For example:

        QSqlQueryModel *model = new QSqlQueryModel;
        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:

        QSqlQueryModel model;
        model.setQuery("SELECT * FROM employee");
        int salary = model.record(4).value("salary").toInt();

The code snippet above extracts the salary field from record 4 in the result set of the query SELECT * from employee. 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 amount 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, Model Example

Nested Class Summary
 
Nested classes/interfaces inherited from class com.trolltech.qt.QSignalEmitter
QSignalEmitter.AbstractSignal, QSignalEmitter.Signal0, QSignalEmitter.Signal1<A>, QSignalEmitter.Signal2<A,B>, QSignalEmitter.Signal3<A,B,C>, QSignalEmitter.Signal4<A,B,C,D>, QSignalEmitter.Signal5<A,B,C,D,E>, QSignalEmitter.Signal6<A,B,C,D,E,F>, QSignalEmitter.Signal7<A,B,C,D,E,F,G>, QSignalEmitter.Signal8<A,B,C,D,E,F,G,H>, QSignalEmitter.Signal9<A,B,C,D,E,F,G,H,I>
 
Field Summary
 
Fields inherited from class com.trolltech.qt.core.QAbstractItemModel
dataChanged, headerDataChanged, layoutAboutToBeChanged, layoutChanged
 
Constructor Summary
QSqlQueryModel()
          Equivalent to QSqlQueryModel(0).
QSqlQueryModel(QObject parent)
          Creates an empty QSqlQueryModel with the given parent.
 
Method Summary
 boolean canFetchMore(QModelIndex parent)
          Returns true if it is possible to read more rows from the database.
 void clear()
          Clears the model and releases any acquired resource.
 int columnCount(QModelIndex parent)
          This function is reimplemented for internal reasons.
 java.lang.Object data(QModelIndex item, int role)
          Returns the value for the specified item and role.
 void fetchMore(QModelIndex parent)
          Fetches more rows from a database.
static QSqlQueryModel fromNativePointer(QNativePointer nativePointer)
          This function returns the QSqlQueryModel instance pointed to by nativePointer
 java.lang.Object headerData(int section, Qt.Orientation orientation, int role)
          Returns the header data for the given role in the section of the header with the specified orientation.
protected  QModelIndex indexInQuery(QModelIndex item)
          Returns the index of the value in the database result set for the given item in the model.
 boolean insertColumns(int column, int count, QModelIndex parent)
          Inserts count columns into the model at position column.
 QSqlError lastError()
          Returns information about the last error that occurred on the database.
 QSqlQuery query()
          Returns the QSqlQuery associated with this model.
protected  void queryChange()
          This virtual function is called whenever the query changes.
 QSqlRecord record()
          Returns an empty record containing information about the fields of the current query.
 QSqlRecord record(int row)
          Returns the record containing information about the fields of the current query.
 boolean removeColumns(int column, int count, QModelIndex parent)
          Removes count columns from the model starting from position column.
 int rowCount(QModelIndex parent)
          If the database supports returning the size of a query (see QSqlDriver::hasFeature()), the amount of rows of the current query is returned.
 boolean setHeaderData(int section, Qt.Orientation orientation, java.lang.Object value, int role)
          Sets the caption for a horizontal header for the specified role to value.
protected  void setLastError(QSqlError error)
          Protected function which allows derived classes to set the value of the last error that occurred on the database to error.
 void setQuery(QSqlQuery query)
          Resets the model and sets the data provider to be the given query.
 void setQuery(java.lang.String query)
          Equivalent to setQuery(query, QSqlDatabase()).
 void setQuery(java.lang.String query, QSqlDatabase db)
          Executes the query query for the given database connection db.
 
Methods inherited from class com.trolltech.qt.gui.QAbstractTableModel
dropMimeData, hasChildren, index, parent
 
Methods inherited from class com.trolltech.qt.core.QAbstractItemModel
beginInsertColumns, beginInsertRows, beginRemoveColumns, beginRemoveRows, buddy, changePersistentIndex, changePersistentIndexList, columnCount, createIndex, createIndex, createIndex, data, data, data, decodeData, encodeData, endInsertColumns, endInsertRows, endRemoveColumns, endRemoveRows, flags, hasChildren, hasIndex, hasIndex, headerData, index, insertColumn, insertColumn, insertColumns, insertRow, insertRow, insertRows, insertRows, itemData, match, match, match, match, mimeData, mimeTypes, persistentIndexList, removeColumn, removeColumn, removeColumns, removeRow, removeRow, removeRows, removeRows, reset, revert, rowCount, setData, setData, setData, setData, setHeaderData, setItemData, setSupportedDragActions, setSupportedDragActions, sibling, sort, sort, span, submit, supportedDragActions, supportedDropActions
 
Methods inherited from class com.trolltech.qt.core.QObject
blockSignals, childEvent, children, connectSlotsByName, customEvent, disposeLater, dumpObjectInfo, dumpObjectTree, dynamicPropertyNames, event, eventFilter, findChild, findChild, findChild, findChildren, findChildren, findChildren, findChildren, installEventFilter, isWidgetType, killTimer, moveToThread, objectName, parent, property, removeEventFilter, setObjectName, setParent, setProperty, signalsBlocked, startTimer, thread, timerEvent
 
Methods inherited from class com.trolltech.qt.QtJambiObject
dispose, disposed, finalize, reassignNativeResources, tr, tr, tr
 
Methods inherited from class com.trolltech.qt.QSignalEmitter
disconnect, disconnect, signalSender
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface com.trolltech.qt.QtJambiInterface
disableGarbageCollection, nativeId, nativePointer, reenableGarbageCollection, setJavaOwnership
 

Constructor Detail

QSqlQueryModel

public QSqlQueryModel()

Equivalent to QSqlQueryModel(0).


QSqlQueryModel

public QSqlQueryModel(QObject parent)

Creates an empty QSqlQueryModel with the given parent.

Method Detail

indexInQuery

protected QModelIndex indexInQuery(QModelIndex item)

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

lastError

public final QSqlError lastError()

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

See Also:
setLastError

query

public final QSqlQuery query()

Returns the QSqlQuery associated with this model.

See Also:
setQuery

record

public final QSqlRecord record()

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

record

public final QSqlRecord record(int row)

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

setLastError

protected final void setLastError(QSqlError error)

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

See Also:
lastError

setQuery

public final void setQuery(java.lang.String query)

Equivalent to setQuery(query, QSqlDatabase()).


setQuery

public final void setQuery(java.lang.String query,
                           QSqlDatabase db)

Executes the query query for the given database connection db. If no 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:

    QSqlQueryModel model;
    model.setQuery("select * from MyTable");
    if (model.lastError().isValid())
        qDebug() << model.lastError();

See Also:
query, queryChange, lastError

setQuery

public void setQuery(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.

See Also:
query, QSqlQuery::isActive, QSqlQuery::setForwardOnly, lastError

canFetchMore

public boolean canFetchMore(QModelIndex parent)

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

parent should always be an invalid QModelIndex.

Overrides:
canFetchMore in class QAbstractItemModel
See Also:
fetchMore

clear

public void clear()

Clears the model and releases any acquired resource.


columnCount

public int columnCount(QModelIndex parent)

This function is reimplemented for internal reasons.

Specified by:
columnCount in class QAbstractItemModel
See Also:
rowCount

data

public java.lang.Object data(QModelIndex item,
                             int role)

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.

Specified by:
data in class QAbstractItemModel
See Also:
lastError

fetchMore

public void fetchMore(QModelIndex parent)

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

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

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

parent should always be an invalid QModelIndex.

Overrides:
fetchMore in class QAbstractItemModel
See Also:
canFetchMore

headerData

public java.lang.Object headerData(int section,
                                   Qt.Orientation orientation,
                                   int role)

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

Overrides:
headerData in class QAbstractItemModel
See Also:
setHeaderData

insertColumns

public boolean insertColumns(int column,
                             int count,
                             QModelIndex parent)

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);
    }

Overrides:
insertColumns in class QAbstractItemModel
See Also:
removeColumns

queryChange

protected void queryChange()

This virtual function is called whenever the query changes. The default implementation does nothing.

query returns the new query.

See Also:
query, setQuery

removeColumns

public boolean removeColumns(int column,
                             int count,
                             QModelIndex parent)

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.

Overrides:
removeColumns in class QAbstractItemModel
See Also:
removeColumn, removeRows, insertColumns, beginRemoveColumns, endRemoveColumns

rowCount

public int rowCount(QModelIndex parent)

If the database supports returning the size of a query (see QSqlDriver::hasFeature()), the amount of rows of the current query is returned. Otherwise, returns the amount of rows currently cached on the client.

parent should always be an invalid QModelIndex.

Specified by:
rowCount in class QAbstractItemModel
See Also:
canFetchMore, QSqlDriver::hasFeature

setHeaderData

public boolean setHeaderData(int section,
                             Qt.Orientation orientation,
                             java.lang.Object value,
                             int role)

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.

Overrides:
setHeaderData in class QAbstractItemModel
See Also:
headerData, data

fromNativePointer

public static QSqlQueryModel fromNativePointer(QNativePointer nativePointer)
This function returns the QSqlQueryModel instance pointed to by nativePointer

Parameters:
nativePointer - the QNativePointer of which object should be returned.

Qt Jambi Home