qml使用c++自定义listmodel数据

qml要使用c++中自定义的model,首先该model类需要继承QAbstractListModel类,然后需要重写其中的三个函数,分别是

int rowCount(const QModelIndex &parent);

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

QHash<int,QByteArray> roleNames();

代码如下:

DriverModel.h

cpp 复制代码
#ifndef DRIVERMODEL_H
#define DRIVERMODEL_H


#include <QStringList>
#include <QObject>
#include <QtQml>


class DriverModel : public QAbstractListModel
{
    Q_OBJECT
public:

    typedef struct DriverData{
        QString type;
        QString desc;
        QString version;
    }DriverData;

    static DriverModel *instance(QObject *parent = nullptr) {
        static DriverModel *instance = nullptr;
        static std::mutex instance_mutex;
        if (instance == nullptr) {
            std::lock_guard<std::mutex> guard(instance_mutex);
            if (instance == nullptr) {
                instance = new DriverModel(parent);
            }
        }
        return instance;
    }

    explicit DriverModel(QObject *parent = nullptr){
        appendItem(QString::fromLocal8Bit("显卡"),"Raden RX220","1.25.0.1");
    }

    enum LIST_ITEM_ROLE
    {
        type = Qt::UserRole+1,
        desc,
        version
    };


public:
    //必须重写三个函数
    int rowCount(const QModelIndex &parent) const override
    {
        Q_UNUSED(parent);
        return m_list.count();
    }
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
    {
        int row = index.row();
        if(row < 0 || row >= m_list.count()) {
            return QVariant();
        }

        switch(role)
        {
        case type:
            return m_list.value(row).type;
        case desc:
            return m_list.value(row).desc;
        case version:
            return m_list.value(row).version;
        default:
            break;
        }

        return QVariant();
    }
    QHash<int,QByteArray> roleNames() const override
    {
        QHash<int, QByteArray> roles;
        roles[desc] = "desc";
        roles[type] = "type";
        roles[version] = "version";
        return roles;
    }

public:
    //追加数据
    void appendItem(const QString& type,const QString& desc,const QString& version)
    {
        DriverData data;
        data.type = type;
        data.desc = desc;
        data.version = version;

        beginInsertRows(QModelIndex(), m_list.size(), m_list.size());
        m_list.append(data);
        endInsertRows();
    }
    //清空模型数据
    void clearModelData() {
        beginResetModel();
        m_list.clear();
        endResetModel();
    }



private:
    QList<DriverData> m_list;

};



#endif // DRIVERMODEL_H

main.cpp

cpp 复制代码
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "DriverModel.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty("driverModel",DriverModel::instance());

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);

    engine.load(url);

    return app.exec();
}

main.qml

cpp 复制代码
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ListView{
        width: parent.width
        height: parent.height
        visible: true
        model: driverModel
        delegate: Item{
            Text{
                id:text1
                text: type
            }
            Text{
                id:text2
                text: desc
                anchors.top: text1.bottom
            }
            Text{
                text: version
                anchors.top: text2.bottom
            }
        }
    }
}
相关推荐
hummhumm6 分钟前
Oracle 第29章:Oracle数据库未来展望
java·开发语言·数据库·python·sql·oracle·database
wainyz15 分钟前
Java NIO操作
java·开发语言·nio
喵叔哟23 分钟前
重构代码之用委托替代继承
开发语言·重构
lzb_kkk29 分钟前
【JavaEE】JUC的常见类
java·开发语言·java-ee
SEEONTIME29 分钟前
python-24-一篇文章彻底掌握Python HTTP库Requests
开发语言·python·http·http库requests
Zfox_30 分钟前
【Linux】进程信号全攻略(二)
linux·运维·c语言·c++
起名字真南1 小时前
【OJ题解】C++实现字符串大数相乘:无BigInteger库的字符串乘积解决方案
开发语言·c++·leetcode
少年负剑去1 小时前
第十五届蓝桥杯C/C++B组题解——数字接龙
c语言·c++·蓝桥杯
cleveryuoyuo1 小时前
AVL树的旋转
c++
tyler_download1 小时前
golang 实现比特币内核:实现基于椭圆曲线的数字签名和验证
开发语言·数据库·golang