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(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);
...

© 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.