在Qt Quick 视图中使用SQL数据库
SQL 模型
Qt SQL 提供了支持 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() 以将 SQL 数据暴露给 QML 前端。例如,以下实现返回给定模型索引对应的数据:
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);
...© 2026 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.