QSqlQueryModel Class ReferenceThe QSqlQueryModel class provides a read-only data model for SQL result sets. Далее... #include <QSqlQueryModel> Inherits: QAbstractTableModel. Inherited by: QSqlTableModel. Открытые функции
Переопределённые открытые функции
Защищенные функции
Дополнительные унаследованные члены
Подробное описание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. Например: 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(); Фрагмент кода выше извлекает поле salary из четвёртой записи, выбранной по запросу 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, and Query Model Example. Описание функций-членовQSqlQueryModel::QSqlQueryModel ( QObject * parent = 0 )Creates an empty QSqlQueryModel with the given parent. QSqlQueryModel::~QSqlQueryModel () [virtual]Удаляет объект и освобождает все выделенные ему ресурсы. See also clear(). bool QSqlQueryModel::canFetchMore ( const QModelIndex & parent = QModelIndex() ) const [virtual]Reimplemented from QAbstractItemModel::canFetchMore(). 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. Эта функция была введена в Qt 4.1. See also fetchMore(). void QSqlQueryModel::clear () [virtual]Clears the model and releases any acquired resource. int QSqlQueryModel::columnCount ( const QModelIndex & index = QModelIndex() ) const [virtual]Reimplemented from QAbstractItemModel::columnCount(). QVariant QSqlQueryModel::data ( const QModelIndex & item, int role = Qt::DisplayRole ) const [virtual]Переопределено из QAbstractItemModel::data(). 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. Смотрите также lastError(). void QSqlQueryModel::fetchMore ( const QModelIndex & parent = QModelIndex() ) [virtual]Reimplemented from QAbstractItemModel::fetchMore(). 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. Эта функция была введена в Qt 4.1. See also canFetchMore(). QVariant QSqlQueryModel::headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const [virtual]Переопределено из QAbstractItemModel::headerData(). Returns the header data for the given role in the section of the header with the specified orientation. See also setHeaderData(). QModelIndex QSqlQueryModel::indexInQuery ( const QModelIndex & item ) const [protected]Возвращает индекс значения в результате, полученном для элемента item модели. Вернёт значение, равное item, если вокруг нет столбцов или строк для вставки, удаления или перемещения. Возвращает неправильный индекс модели, если item выходит за границы или если item не является указателем на значение в результирующем наборе. See also QSqlTableModel::indexInQuery(), insertColumns(), and removeColumns(). bool QSqlQueryModel::insertColumns ( int column, int count, const QModelIndex & parent = QModelIndex() ) [virtual]Reimplemented from QAbstractItemModel::insertColumns(). 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(). QSqlError QSqlQueryModel::lastError () constВозвращает информацию о последней ошибке, случившейся при работе с базой данных. See also setLastError() and query(). QSqlQuery QSqlQueryModel::query () constReturns the QSqlQuery associated with this model. Смотрите также setQuery(). void QSqlQueryModel::queryChange () [virtual protected]This virtual function is called whenever the query changes. Реализация по умолчанию ничего не делает. query() returns the new query. See also query() and setQuery(). QSqlRecord QSqlQueryModel::record ( int row ) constReturns 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(). 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(). bool QSqlQueryModel::removeColumns ( int column, int count, const QModelIndex & parent = QModelIndex() ) [virtual]Переопределено из QAbstractItemModel::removeColumns(). 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. int QSqlQueryModel::rowCount ( const QModelIndex & parent = QModelIndex() ) const [virtual]Переопределено из QAbstractItemModel::rowCount(). 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. Эта функция была введена в Qt 4.1. See also canFetchMore() and QSqlDriver::hasFeature(). bool QSqlQueryModel::setHeaderData ( int section, Qt::Orientation orientation, const QVariant & value, int role = Qt::EditRole ) [virtual]Переопределена из QAbstractItemModel::setHeaderData(). 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 headerData() and data(). 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. Смотрите также 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(), and 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(); See also query(), queryChange(), and lastError(). |
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |