在 Qt QML TableView 中显示 QSqlTableModel 自定义数据

本指南将演示如何在 Qt 中使用自定义的 QSqlTableModel 类,并在 QML 的 TableView 中显示自定义数据。通过重写 data() 函数并定义 Qt.UserRole,您可以轻松地将自定义信息添加到表格视图中。

步骤 1: 创建自定义 QSqlTableModel 类

首先,创建一个自定义的 QSqlTableModel 类,并重写 data() 函数。在这个函数中,您需要定义 Qt.UserRole 并返回您想要显示的自定义数据。

#include <QSqlTableModel>
#include <QVariant>

class CustomSqlTableModel : public QSqlTableModel
{
public:
    CustomSqlTableModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase())
        : QSqlTableModel(parent, db)
    {}

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
    {
        if (role == Qt::UserRole) {
            // 返回自定义数据,可以根据需要进行修改
            return QSqlTableModel::data(index, Qt::DisplayRole).toString() + ' (Custom)';
        }

        return QSqlTableModel::data(index, role);
    }
};

步骤 2: 在 QML 中创建 TableView 并绑定模型

在您的 QML 文件中,创建一个 TableView 并将其绑定到您创建的自定义 QSqlTableModel。

import QtQuick 2.12
import QtQuick.Controls 2.12

TableView {
    id: tableView
    anchors.fill: parent

    model: customModel
    TableViewColumn {
        role: 'displayRole'
        title: 'Data'
        width: 100
    }
}

Component.onCompleted: {
    customModel.query = 'SELECT * FROM your_table'
    customModel.select()
}

步骤 3: 在 C++ 中绑定 QML TableView 和模型

在您的 C++ 代码中,将 QML 中的 TableView 绑定到自定义的 QSqlTableModel。

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlTableModel>
#include <QSqlRecord>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    // 创建数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase('QSQLITE');
    db.setDatabaseName(':memory:');

    // 打开数据库
    if (!db.open()) {
        qDebug() << 'Failed to open database:' << db.lastError().text();
        return -1;
    }

    // 创建表格
    QSqlQuery query;
    query.exec('CREATE TABLE your_table (id INT PRIMARY KEY, name VARCHAR(255))');

    // 插入数据
    query.exec('INSERT INTO your_table VALUES (1, 'John')');
    query.exec('INSERT INTO your_table VALUES (2, 'Alice')');
    query.exec('INSERT INTO your_table VALUES (3, 'Bob')');

    // 创建自定义的 QSqlTableModel 类
    CustomSqlTableModel customModel;
    customModel.setTable('your_table');

    // 创建 QML 引擎
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty('customModel', &customModel);
    engine.load(QUrl(QStringLiteral('qrc:/main.qml')));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

运行程序

现在,运行您的程序,您应该能在 QML 中的 TableView 中看到数据,并在每个单元格中显示您在 data() 函数中定义的自定义数据。

注意:

  • 确保将 'your_table' 替换为您的实际表名。
  • 您可以在 data() 函数中返回任何您想要显示的自定义数据,例如字符串、数值或其他类型。
  • 使用 Qt.UserRole 来表示自定义数据,因为它不会与 Qt 的默认角色冲突。

通过遵循这些步骤,您可以在 Qt QML 的 TableView 中轻松显示 QSqlTableModel 的自定义数据。

Qt QSqlTableModel 自定义数据显示在 QML TableView