QML 使用自定义ListModel

1.简介

QAbstractListModel类提供了一个抽象模型,可以子类化它来创建一维列表模型。

以下示例实现一个最简单的ListModel,需要重写以下几个方法。

2.自定义ListModel

#ifndef MYLISTMODEL_H
#define MYLISTMODEL_H

#include <QAbstractListModel>
#include <QList>

//自定义抽象数据类型
class Data
{
public:
    Data(const QString &name, int value) : m_name(name),m_value(value){

    };
    QString m_name;
    qint32 m_value;
};

class MyListModel : public QAbstractListModel
{
    Q_OBJECT

public:
    enum RoleNames{
        Name = Qt::DisplayRole+1,
        Value
    };

    // Basic functionality:
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;

    virtual QHash<int, QByteArray> roleNames() const override;

     explicit MyListModel(QObject *parent = nullptr);

private:
    QList<Data> m_data;
};

#endif // MYLISTMODEL_H
#include "mylistmodel.h"

MyListModel::MyListModel(QObject *parent)
    : QAbstractListModel(parent)
{
    m_data.append(Data("zhangsan",12));    //放入数据
    m_data.append(Data("lisi", 13));
    m_data.append(Data("wangwu", 14));
}

int MyListModel::rowCount(const QModelIndex &parent) const
{
    // For list models only the root node (an invalid parent) should return the list's size. For all
    // other (valid) parents, rowCount() should return 0 so that it does not become a tree model.
    if (parent.isValid())
        return 0;

    return m_data.count();
}

QVariant MyListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if(role == MyListModel::Name)
        return m_data[index.row()].m_name;
    else if(role == MyListModel::Value)
        return m_data[index.row()].m_value;

    return QVariant();
}

QHash<int, QByteArray> MyListModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles.insert(MyListModel::Name,"name");    //C++端使用枚举,QML端使用QString
    roles.insert(MyListModel::Value,"value");

    return roles;
}

在main.cpp中注册。

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

    MyListModel model;

    QQmlApplicationEngine engine;
    qmlRegisterType<MyListModel>("MyListModel", 1, 0, "MyListModel");
    engine.rootContext()->setContextProperty("myModel",&model);//设置全局访问

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

3.QML中使用

直接使用name 和value就能访问数据了。

import MyListModel 1.0

Window {
    id: window
    objectName: "window"
    visible: true
    width: 400
    height: 500
    title: qsTr("Hello World")


    ListView{
        width: 200
        height: 300
        model: myModel
        delegate: Text{
            text: name + " " + value
        }
    }
}

4.运行结果

猜你喜欢

转载自blog.csdn.net/wzz953200463/article/details/129802109