QT创建只读模型通过列表视图(ListView)与表格视图(TableView)显示字符串列表(StringList)数据
这里实现的模型是一个基于标准QStringListModel类的简单的、无层次的只读数据模型。它有一个QStringList作为它的内部数据源,并且只实现构建一个功能模型所需要的东西。 为了使实现更容易,我们子类化QAbstractListModel,因为它为列表模型定义了合理的默认行为,并且它公开了一个比QAbstractItemModel类更简单的接口。
在实现模型时,重要的是要记住QAbstractItemModel本身并不存储任何数据,它只是提供视图用来访问数据的接口。对于最小只读模型,只需要实现一些函数,因为大多数接口都有默认实现
QT+=widgets
HEADERS += \
stringlistmodel.h
SOURCES += \
main.cpp \
stringlistmodel.cpp
#ifndef STRINGLISTMODEL_H
#define STRINGLISTMODEL_H
#include
#include
class StringListModel : public QAbstractListModel
{
Q_OBJECT
public:
StringListModel(const QStringList &strings,QObject *parent =0):
QAbstractListModel(parent),stringList(strings){}
int rowCount(const QModelIndex &parent=QModelIndex()) const;
QVariant data(const QModelIndex &index,int role) const;
QVariant headerData(int section,Qt::Orientation orientation,
int role=Qt::DisplayRole) const;
private:
QStringList stringList;
};
#endif // STRINGLISTMODEL_H
#include "stringlistmodel.h"
//创建只读模型。。。by txwtech
//StringListModel::StringListModel()
//{
//}
int StringListModel::rowCount(const QModelIndex &parent) const
{
return stringList.count();
}
QVariant StringListModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
{
return QVariant();
}
if(index.row()==stringList.count())
{
return QVariant();
}
if(role==Qt::DisplayRole)
{
return stringList.at(index.row());
}
else
{
return QVariant();
}
}
QVariant StringListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(role!=Qt::DisplayRole)
return QVariant();
if(orientation==Qt::Horizontal)
return QString("Column is %1").arg(section);
else
return QString("Row is %1").arg(section);
}
main.cpp
#include
#include
#include
#include
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QStringList list;
list
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?