您当前的位置: 首页 >  qt

txwtech

暂无认证

  • 2浏览

    0关注

    813博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

QT创建只读模型通过列表视图与表格视图显示字符串列表数据

txwtech 发布时间:2022-10-03 22:29:19 ,浏览量:2

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            
关注
打赏
1665060526
查看更多评论
0.0378s