- Qt 6.9
- Qt Quick
- Important Concepts In Qt Quick - Data - Models, Views and Data Storage
- Using C++ Models with Qt Quick Views
- Qt 6.9.2 Reference Documentation

Models and Views in Qt Quick ◦ Qt Labs FolderListModel QML Types

# Using C++ Models with Qt Quick Views

## Data Provided In A Custom C++ Model

Models can be defined in C++ and then made available to QML. This is useful for exposing existing C++ data models or otherwise complex datasets to QML.

A C++ model class can be defined as a QStringList, a QVariantList, a QObjectList or a QAbstractItemModel. The first three are useful for exposing simpler datasets, while QAbstractItemModel provides a more flexible solution for more complex models.

Here is a video tutorial that takes you through the whole process of exposing a C++ model to QML:

### QStringList-based Model

A model may be a simple QStringList, which provides the contents of the list via the modelData role.

Here is a ListView with a delegate that references its model item's value using the `modelData` role:

     ListView {
         width: 100
         height: 100
         required model

         delegate: Rectangle {
             required property string modelData
             height: 25
             width: 100
             Text { text: parent.modelData }
         }
     }

A Qt application can load this QML document and set the value of `myModel` to a QStringList:

         QStringList dataList = {
             "Item 1",
             "Item 2",
             "Item 3",
             "Item 4"
         };

         QQuickView view;
         view.setInitialProperties({{ "model", QVariant::fromValue(dataList) }});

The complete source code for this example is available in examples/quick/models/stringlistmodel within the Qt install directory.

Note: There is no way for the view to know that the contents of a QStringList have changed. If the QStringList changes, it will be necessary to reset the model by setting the view's `model` property again.

### QVariantList-based Model

A model may be a single QVariantList, which provides the contents of the list via the modelData role.

The API works just like with QStringList, as shown in the previous section.

Note: There is no way for the view to know that the contents of a QVariantList have changed. If the QVariantList changes, it will be necessary to reset the model.

### QObjectList-based Model

A list of QObject* values can also be used as a model. A QList<QObject*> provides the properties of the objects in the list as roles.

The following application creates a `DataObject` class with Q_PROPERTY values that will be accessible as named roles when a QList<DataObject*> is exposed to QML:

     class DataObject : public QObject
     {
         Q_OBJECT

         Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
         Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged)
         ...
     };

     int main(int argc, char ** argv)
     {
         QGuiApplication app(argc, argv);

         const QStringList colorList = {"red",
                                        "green",
                                        "blue",
                                        "yellow"};

         const QStringList moduleList = {"Core", "GUI", "Multimedia", "Multimedia Widgets", "Network",
                                         "QML", "Quick", "Quick Controls", "Quick Dialogs",
                                         "Quick Layouts", "Quick Test", "SQL", "Widgets", "3D",
                                         "Android Extras", "Bluetooth", "Concurrent", "D-Bus",
                                         "Gamepad", "Graphical Effects", "Help", "Image Formats",
                                         "Location", "Mac Extras", "NFC", "OpenGL", "Platform Headers",
                                         "Positioning", "Print Support", "Purchasing", "Quick Extras",
                                         "Quick Timeline", "Quick Widgets", "Remote Objects", "Script",
                                         "SCXML", "Script Tools", "Sensors", "Serial Bus",
                                         "Serial Port", "Speech", "SVG", "UI Tools", "WebEngine",
                                         "WebSockets", "WebView", "Windows Extras", "XML",
                                         "XML Patterns", "Charts", "Network Authorization",
                                         "Virtual Keyboard", "Quick 3D", "Quick WebGL"};

         QList<QObject *> dataList;
         for (const QString &module : moduleList)
             dataList.append(new DataObject("Qt " + module, colorList.at(rand() % colorList.length())));

         QQuickView view;
         view.setResizeMode(QQuickView::SizeRootObjectToView);
         view.setInitialProperties({{ "model", QVariant::fromValue(dataList) }});
         ...

The QObject* is available as the `modelData` property. As a convenience, the properties of the object are also made available directly in the delegate's context. Here, `view.qml` references the `DataModel` properties in the ListView delegate:

     ListView {
         id: listview
         width: 200; height: 320
         required model
         ScrollBar.vertical: ScrollBar { }

         delegate: Rectangle {
             width: listview.width; height: 25

             required color
             required property string name

             Text { text: parent.name }
         }
     }

Note the use of the `color` property. You can require existing properties by declaring them as `required` in a derived type.

The complete source code for this example is available in examples/quick/models/objectlistmodel within the Qt install directory.

Note: There is no way for the view to know that the contents of a QList has changed. If the QList changes, it is necessary to reset the model by setting the `model` property again.

### QAbstractItemModel Subclass

A model can be defined by subclassing QAbstractItemModel. This is the best approach if you have a more complex model that cannot be supported by the other approaches. A QAbstractItemModel can also automatically notify a QML view when the model data changes.

The roles of a QAbstractItemModel subclass can be exposed to QML by reimplementing QAbstractItemModel::roleNames().

Here is an application with a QAbstractListModel subclass named `AnimalModel`, which exposes the type and sizes roles. It reimplements QAbstractItemModel::roleNames() to expose the role names, so that they can be accessed via QML:

     class Animal
     {
     public:
         Animal(const QString &type, const QString &size);
         ...
     };

     class AnimalModel : public QAbstractListModel
     {
         Q_OBJECT
     public:
         enum AnimalRoles {
             TypeRole = Qt::UserRole + 1,
             SizeRole
         };

         AnimalModel(QObject *parent = nullptr);
         ...
     };

     QHash<int, QByteArray> AnimalModel::roleNames() const {
         QHash<int, QByteArray> roles;
         roles[TypeRole] = "type";
         roles[SizeRole] = "size";
         return roles;
     }

     int main(int argc, char ** argv)
     {
         QGuiApplication app(argc, argv);

         AnimalModel model;
         model.addAnimal(Animal("Wolf", "Medium"));
         model.addAnimal(Animal("Polar bear", "Large"));
         model.addAnimal(Animal("Quoll", "Small"));

         QQuickView view;
         view.setResizeMode(QQuickView::SizeRootObjectToView);
         view.setInitialProperties({{"model", QVariant::fromValue(&model)}});
         ...

This model is displayed by a ListView delegate that accesses the type and size roles:

     ListView {
         width: 200; height: 250

         required model

         delegate: Text {
             required property string type
             required property string size

             text: "Animal: " + type + ", " + size
         }
     }

QML views are automatically updated when the model changes. Remember the model must follow the standard rules for model changes and notify the view when the model has changed by using QAbstractItemModel::dataChanged(), QAbstractItemModel::beginInsertRows(), and so on. See the Model subclassing reference for more information.

The complete source code for this example is available in examples/quick/models/abstractitemmodel within the Qt install directory.

QAbstractItemModel presents a hierarchy of tables, but the views currently provided by QML can only display list data. In order to display the child lists of a hierarchical model, use the DelegateModel QML type, which provides the following properties and functions to be used with list models of QAbstractItemModel type:

- hasModelChildren role property to determine whether a node has child nodes.
- DelegateModel::rootIndex allows the root node to be specified
- DelegateModel::modelIndex() returns a QModelIndex which can be assigned to DelegateModel::rootIndex
- DelegateModel::parentModelIndex() returns a QModelIndex which can be assigned to DelegateModel::rootIndex

### SQL Models

Qt provides C++ classes that support SQL data models. These classes work transparently on the underlying SQL data, reducing the need to run SQL queries for basic SQL operations such as create, insert, or update. For more details about these classes, see Using the SQL Model Classes.

Although the C++ classes provide complete feature sets to operate on SQL data, they do not provide data access to QML. So you must implement a C++ custom data model as a subclass of one of these classes, and expose it to QML either as a type or context property.

#### Read-only Data Model

The custom model must reimplement the following methods to enable read-only access to the data from QML:

- roleNames() to expose the role names to the QML frontend. For example, the following version returns the selected table's field names as role names:

        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() to expose SQL data to the QML frontend. For example, the following implementation returns data for the given model index:

       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;
       }

The QSqlQueryModel class is good enough to implement a custom read-only model that represents data in an SQL database. The chat tutorial example demonstrates this very well by implementing a custom model to fetch the contact details from an SQLite database.

#### Editable Data Model

QSqlTableModel implements setData() as described below.

Depending on the EditStrategy used by the model, the changes are either queued for submission later or submitted immediately.

You can also insert new data into the model by calling QSqlTableModel::insertRecord(). In the following example snippet, a QSqlRecord is populated with book details and appended to the model:

     ...
     QSqlRecord newRecord = record();
     newRecord.setValue("author", "John Grisham");
     newRecord.setValue("booktitle", "The Litigators");
     insertRecord(rowCount(), newRecord);
     ...

### Exposing C++ Data Models to QML

The above examples use required properties on the view to set model values directly in QML components. An alternative to this is to register the C++ model class as a QML type (see Defining QML Types from C++). This allows the model classes to be created directly as types within QML:

C++ |
     class MyModel : public QAbstractItemModel
     {
         Q_OBJECT
         QML_ELEMENT

         // [...]
     }
QML |
     MyModel {
         id: myModel
     }
     ListView {
         width: 200; height: 250
         model: myModel
         delegate: Text {
             required property string someProperty
             text: someProperty
         }
     }

See Writing QML Extensions with C++ for details on writing QML types in C++.

### Changing Model Data

Besides the `roleNames()` and `data()`, editable models must reimplement the setData method to save changes to existing model data. The following version of the method checks if the given model index is valid and the `role` is equal to Qt::EditRole:

     bool EditableModel::setData(const QModelIndex &index, const QVariant &value, int role)
     {
         if (index.isValid() && role == Qt::EditRole) {
             // Set data in model here. It can also be a good idea to check whether
             // the new value actually differs from the current value
             if (m_entries[index.row()] != value.toString()) {
                 m_entries[index.row()] = value.toString();
                 emit dataChanged(index, index, { Qt::EditRole, Qt::DisplayRole });
                 return true;
             }
         }
         return false;
     }

Note: It is important to emit the dataChanged() signal after saving the changes.

Unlike the C++ item views such as QListView or QTableView, the `setData()` method must be explicitly invoked from QML delegates whenever appropriate. This is done by simply assigning a new value to the corresponding model property.

     ListView {
         anchors.fill: parent
         model: EditableModel {}
         delegate: TextField {
             width: ListView.view.width
             text: model.edit
             onAccepted: model.edit = text
         }
     }

Note: The `edit` role is equal to Qt::EditRole. See roleNames() for the built-in role names. However, real life models would usually register custom roles.

Models and Views in Qt Quick ◦ Qt Labs FolderListModel QML Types