QSqlQueryModel Class

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

头: #include <QSqlQueryModel>
CMake: find_package(Qt6 REQUIRED COMPONENTS Sql)
target_link_libraries(mytarget PRIVATE Qt6::Sql)
qmake: QT += sql
继承: QAbstractTableModel
继承者: QSqlTableModel

公共函数

QSqlQueryModel (QObject * parent = nullptr)
virtual ~QSqlQueryModel ()
virtual void clear ()
QSqlError lastError () const
const QSqlQuery & query () const
QSqlRecord record (int row ) const
QSqlRecord record () const
void setQuery (QSqlQuery && query )
void setQuery (const QString & query , const QSqlDatabase & db = QSqlDatabase())

重实现公共函数

virtual bool canFetchMore (const QModelIndex & parent = QModelIndex()) const override
virtual int columnCount (const QModelIndex & index = QModelIndex()) const override
virtual QVariant data (const QModelIndex & item , int role = Qt::DisplayRole) const override
virtual void fetchMore (const QModelIndex & parent = QModelIndex()) override
virtual QVariant headerData (int section , Qt::Orientation orientation , int role = Qt::DisplayRole) const override
virtual bool insertColumns (int column , int count , const QModelIndex & parent = QModelIndex()) override
virtual bool removeColumns (int column , int count , const QModelIndex & parent = QModelIndex()) override
virtual QHash<int, QByteArray> roleNames () const override
virtual int rowCount (const QModelIndex & parent = QModelIndex()) const override
virtual bool setHeaderData (int section , Qt::Orientation orientation , const QVariant & value , int role = Qt::EditRole) override

保护函数

virtual QModelIndex indexInQuery (const QModelIndex & item ) const
virtual void queryChange ()
void setLastError (const QSqlError & error )

详细描述

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 。例如:

    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 name, salary 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 SELECT query. Since salary is the 2nd column (or column index 1), we can rewrite the last line as follows:

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

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

The 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 () 了解更多信息。

另请参阅 QSqlTableModel , QSqlRelationalTableModel , QSqlQuery , 模型/视图编程 ,和 Query Model Example .

成员函数文档编制

[explicit] QSqlQueryModel:: QSqlQueryModel ( QObject * parent = nullptr)

Creates an empty QSqlQueryModel with the given parent .

[虚拟] QSqlQueryModel:: ~QSqlQueryModel ()

销毁对象并释放任何分配资源。

另请参阅 clear ().

[override virtual] bool QSqlQueryModel:: canFetchMore (const QModelIndex & parent = QModelIndex()) const

重实现: QAbstractItemModel::canFetchMore(const QModelIndex &parent) const .

返回 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 .

另请参阅 fetchMore ().

[虚拟] void QSqlQueryModel:: clear ()

Clears the model and releases any acquired resource.

[override virtual] int QSqlQueryModel:: columnCount (const QModelIndex & index = QModelIndex()) const

重实现: QAbstractItemModel::columnCount(const QModelIndex &parent) const .

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

重实现: QAbstractItemModel::data(const QModelIndex &index, int role) const .

Returns the value for the specified item and role .

item is out of bounds or if an error occurred, an invalid QVariant 被返回。

另请参阅 lastError ().

[override virtual] void QSqlQueryModel:: fetchMore (const QModelIndex & parent = QModelIndex())

重实现: QAbstractItemModel::fetchMore (const 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 result set, you can use the following:

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

parent should always be an invalid QModelIndex .

另请参阅 canFetchMore ().

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

重实现: QAbstractItemModel::headerData(int section, Qt::Orientation orientation, int role) const .

Returns the header data for the given rolesection of the header with the specified orientation .

另请参阅 setHeaderData ().

[virtual protected] QModelIndex QSqlQueryModel:: indexInQuery (const QModelIndex & item ) const

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.

另请参阅 QSqlTableModel::indexInQuery (), insertColumns (),和 removeColumns ().

[override virtual] bool QSqlQueryModel:: insertColumns ( int column , int count , const QModelIndex & parent = QModelIndex())

重实现: QAbstractItemModel::insertColumns (int column, int count, const QModelIndex &parent).

插入 count columns into the model at position columnparent parameter must always be an invalid QModelIndex , since the model does not support parent-child relationships.

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

另请参阅 removeColumns ().

QSqlError QSqlQueryModel:: lastError () const

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

另请参阅 setLastError () 和 query ().

const QSqlQuery &QSqlQueryModel:: query () const

Returns a reference to the const QSqlQuery object associated with this model.

另请参阅 setQuery ().

[virtual protected] void QSqlQueryModel:: queryChange ()

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

query () returns the new query.

另请参阅 query () 和 setQuery ().

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.

另请参阅 QSqlRecord::isEmpty ().

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.

另请参阅 QSqlRecord::isEmpty ().

[override virtual] bool QSqlQueryModel:: removeColumns ( int column , int count , const QModelIndex & parent = QModelIndex())

重实现: QAbstractItemModel::removeColumns (int column, int count, const QModelIndex &parent).

移除 count columns from the model starting from position columnparent 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 .

返回 true if the columns were removed; otherwise returns false .

[override virtual] QHash < int , QByteArray > QSqlQueryModel:: roleNames () const

重实现: QAbstractItemModel::roleNames() const .

返回模型的角色名称。

Qt defines only one role for the QSqlQueryModel :

Qt 角色 QML 角色名称
Qt::DisplayRole display

[override virtual] int QSqlQueryModel:: rowCount (const QModelIndex & parent = QModelIndex()) const

重实现: QAbstractItemModel::rowCount(const QModelIndex &parent) const .

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

parent should always be an invalid QModelIndex .

另请参阅 canFetchMore () 和 QSqlDriver::hasFeature ().

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

重实现: QAbstractItemModel::setHeaderData (int section, Qt::Orientation orientation, const QVariant &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 ).

返回 true if orientation is Qt::Horizontal 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.

另请参阅 headerData () 和 data ().

[protected] void QSqlQueryModel:: 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 .

另请参阅 lastError ().

[since 6.2] void QSqlQueryModel:: 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.

注意: Calling setQuery() will remove any inserted columns.

该函数在 Qt 6.2 引入。

另请参阅 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.

范例:

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

另请参阅 query (), queryChange (),和 lastError ().