1.新建一个listmodel
会自动创建mylistmodel的头文件和源文件
其中
//返回数据的大小
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;
2.写个MyData类,包含所需要的字段 并实现各种重写方法
mylistmodel.h
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_OBJECTpublic:
enum MyRoleName{
Name = Qt::DisplayRole +1,
Value
};explicit MyListModel(QObject *parent = nullptr);
//单例 方便调用
static MyListModel *getInstance();// 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<MyData> m_data; //存储数据};
mylistmodel.cpp
#include "mylistmodel.h"
MyListModel::MyListModel(QObject *parent)
: QAbstractListModel(parent)
{
//加载数据
m_data.append(MyData("张三",111));
m_data.append(MyData("李四",111));
m_data.append(MyData("陈三",111));
m_data.append(MyData("王三",111));
m_data.append(MyData("顾三",111));
}MyListModel *MyListModel::getInstance()
{
static MyListModel *obj = new MyListModel;
return obj;
}
//元素的个数,或者说是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;// FIXME: Implement me!
return m_data.count();
}QVariant MyListModel::data(const QModelIndex &index, int role) const
{
//QModelIndex 是一个二维坐标(0,0) //row index column index
if (!index.isValid())
return QVariant();//role 会调用数据嘛
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;
}
3.再main.cpp中注册 以便qml中好访问
qmlRegisterSingletonInstance("MyModel",1,0,"MyListModel22",MyListModel::getInstance());
4.再qml中使用
import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.12
import MyModel 1.0Window {
visible: true
width: 640
height: 480
title: qsTr("自定义model")// ListModel
ListView {
width:200
height:160
//model:["zhangsan","lisi","wangwu"] //model 的大小model: MyListModel22
delegate: Text { //重绘每一项
id: txt
text: name + " " +value
}
}
}