利用Qt Quick 视图使用 SQL 数据库
SQL 模型
Qt 提供支持 SQL 数据模型的 C++ 类。这些类可在底层 SQL 数据上透明地工作,从而减少了为基本 SQL 操作(如创建、插入或更新)运行 SQL 查询的需要。有关这些类的更多详情,请参阅使用 SQL 模型类。
虽然 C++ 类提供了操作 SQL 数据的完整功能集,但它们不提供对 QML 的数据访问。因此,你必须把 C++ 自定义数据模型作为这些类的子类来实现,并把它作为类型或上下文属性暴露给 QML。
只读数据模型
自定义模型必须重新实现以下方法,以便从 QML 只读访问数据:
- roleNames() 向 QML 前端公开角色名称。例如,以下版本将所选表的字段名作为角色名返回:
QHash<int, QByteArray> SqlQueryModel::roleNames() const { QHash<int, QByteArray> roles; // record() returns an empty QSqlRecord for (int i = 0; i < this->record().count(); i ++) { roles.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8()); } return roles; }
- data() 向 QML 前端公开 SQL 数据。例如,以下实现返回给定模型索引的数据:
QVariant SqlQueryModel::data(const QModelIndex &index, int role) const { QVariant value; if (index.isValid()) { if (role < Qt::UserRole) { value = QSqlQueryModel::data(index, role); } else { int columnIdx = role - Qt::UserRole - 1; QModelIndex modelIndex = this->index(index.row(), columnIdx); value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole); } } return value; }
QSqlQueryModel 类足以实现表示 SQL 数据库中数据的自定义只读模型。聊天教程示例很好地演示了这一点,它实现了一个自定义模型,可从 SQLite 数据库中获取联系人详细信息。
可编辑数据模型
QSqlTableModel 为单个数据库表提供了一个可编辑的数据模型,并实现了模型/视图编程概述文档中描述的 setData()。
根据模型使用的EditStrategy ,更改会排队等待稍后提交或立即提交。
您还可以通过调用QSqlTableModel::insertRecord() 向模型中插入新数据。在下面的示例代码段中,QSqlRecord ,并将其添加到模型中:
... QSqlRecord newRecord = record(); newRecord.setValue("author", "John Grisham"); newRecord.setValue("booktitle", "The Litigators"); insertRecord(rowCount(), newRecord); ...
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.