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.