The ListView in Qt Quick is a very useful component that can quickly present the list view, and the C++ data model is also an important part of the Qt framework. This article will introduce how to use Q...

The ListView in Qt Quick is a very useful component that can quickly present the list view, and the C++ data model is also an important part of the Qt framework. This article will introduce how to use the C++ model class to realize the data binding of ListView in Qt Quick.

First, we need to create a data model class in C++, which needs to inherit from QAbstractListModel. Suppose our model class is MyModel, the code is as follows:

class MyModel : public QAbstractListModel
{
    Q_OBJECT
public:
    explicit MyModel(QObject *parent = nullptr);
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
private:
    QList<QString> m_dataList;
};

Among them, the rowCount function returns the total number of rows of data, and the data function returns the data of the corresponding row and column.

Next, in QML, we need to register our data model class through QML Register Type for later use. code show as below:

import QtQuick 2.15
import MyModel 1.0 // 引入 C++ 类

ListView {
    width: 200
    height: 400
    model: myModel
}

MyModel {
    id: myModel
}

In the above code &#x

Guess you like

Origin blog.csdn.net/update7/article/details/130097238