Qt_Note23_QML_自定义Model控件

本文介绍了如何在Qt中创建一个自定义的Model控件MyListModel,包括类定义、实例化和在QML中的使用,以及与ListView的数据绑定。
摘要由CSDN通过智能技术生成

mylistmodel.h

#ifndef MYLISTMODEL_H
#define MYLISTMODEL_H

#include <QAbstractListModel>

class MyData {
public:
    MyData(QString s,int v): m_string(s),m_value(v){

    }
    QString m_string;
    int m_value;
};

class MyListModel : public QAbstractListModel
{
    Q_OBJECT

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

    explicit MyListModel(QObject *parent = nullptr);

    static MyListModel *getInstance();

    // Header:
//    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;

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

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

    QHash<int,QByteArray> roleNames() const override;
private:
//    QList<QString> m_data;
    QList<MyData> m_data;
//    QHash<int,QByteArray> m_roles;
};

#endif // MYLISTMODEL_H

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "mylistmodel.h"

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

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

//    engine.rootContext()->setContextProperty("MyListModel",MyListModel::getInstance());
    qmlRegisterType<MyListModel>("MyModel",1,0,"MyListModel");
    qmlRegisterSingletonInstance("MyModel",1,0,"MyListModel",MyListModel::getInstance());

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

mylistmodel.cpp

#include "mylistmodel.h"

MyListModel::MyListModel(QObject *parent)
    : QAbstractListModel(parent)
{
    m_data.append(MyData("zhangsan",111));
    m_data.append(MyData("lisi",222));
    m_data.append(MyData("wangwu",333));
    m_data.append(MyData("test test",123123123));
}

MyListModel *MyListModel::getInstance()
{
    static MyListModel* obj = new MyListModel;
    return obj;
}

//QVariant MyListModel::headerData(int section, Qt::Orientation orientation, int role) const
//{
//    // FIXME: Implement me!
//}

// 元素的个数 或者说是model的大小/长度
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();

    // FIXME: Implement me!
}

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

    if(role == MyRoleName::Name){
        return m_data[index.row()].m_string;
    }else if (role == MyRoleName::Value) {
        return m_data[index.row()].m_value;
    }
    // FIXME: Implement me!
    return QVariant();
}

QHash<int, QByteArray> MyListModel::roleNames() const
{
    QHash<int,QByteArray> roles;
    roles.insert(MyRoleName::Name, "name"); //字符串是QML端用
    roles.insert(MyRoleName::Value, "value");   //枚举是CPP来判断
    return roles;
}

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import MyModel 1.0

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

    ListView {
        width: 200
        height: 300
//        model: ["zhangsan", "lisi", "wangwu"]   //rowcount可以理解为model的大小
//        model: ListModel {
//            ListElement {
//                name: "zhangsan"
//                value: "111"
//            }
//            ListElement {
//                name: "lisi"
//                value: "2"
//            }
//        }
        model: MyListModel

        delegate: Text {
            id: txt
            text: name + " " + value
        }
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可可西里啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值