派生QAbstractProxyModel小例

本文通过一个小例子介绍了如何派生QAbstractProxyModel来创建代理模型,实现对源模型索引的映射。主要任务包括重载mapToSource()和mapFromSource()函数,以及实现QAbstractItemModel的最小接口,如index(), parent(), rowCount(), columnCount()。示例代码中展示了RevertProxyModel类的实现细节。" 2147164,208687,使用VTK库构建MFC应用实践,"['MFC开发', 'VTK', '图形渲染', '交互设计']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

派生QAbstractProxyModel小例

対源模型的代理本质上就是建立代理模型的索引与源模型的索引之间的映射关系。
定义QAbstractProxyModel的派生类时,需要完成两项任务:
1)、重载纯虚函数 mapToSource()和 mapFromSource(),定义代理模型索引与源模型索引之间的映射关系。
2)、实现QAbstractItemModel的最小接口。因为QAbstractProxyModel是QAbstractItemModel的子类,
从前者派生出的代理模型必须实现所有模型都应该实现的最小接口:
    index(),parent(),rowCount(),columnCount(),data()

/********************************************************************************************/

//widget.h 	

#ifndef WIDGET_H
#define WIDGET_H
#include <QAbstractProxyModel>
#include <QVector>
class RevertProxyModel : public QAbstractProxyModel
{
  
  
    Q_OBJECT
public:
    RevertProxyModel(QObject *parent = 0);
    QModelIndex mapToSource(const QModelIndex &proxy_index) const;
    QModelIndex mapFromSource(const QModelIndex &source_index) const;
    QModelIndex index(int row,int column,const QModelIndex &proxy_index) const;
    QModelIndex parent(const QModelIndex & proxy_child) const;
    int rowCount(const QModelIndex &proxy_parent) const;
    int columnCount(const QModelIndex &proxy_parent) const;
private:
    int register_index(const QModelIndex &source_index) const;
    mutable QVector<QModelIndex> vector; //为使5个重载的常量函数能够修改vector,必须mutable
};
//在此没有重载data()函数,因为QAbstractProxyModel已经实现了该函数
/**
    QVariant QAbstractProxyModel::data(const QModelIndex &proxyIndex,
                                       int role) const{
   
   
        Q_D(const QAbstractProxyModel);
        return d->model->data(mapToSource(proxyIndex), role);
    }
**/
#endif // WIDGET_H

//widget.cpp

#include "widget.h"
#include <QFile>
#include <QTextStream>
#include <QModelIndex>
#define DEBUG
#ifdef DEBUG
static QFile file("log.text");
static QTextStream stream(&file);
#endif
RevertProxyModel::RevertProxyModel(QObject *parent)
    : QAbstractProxyModel(parent)
{
   
   
    vector.clear();
#ifdef DEBUG
<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值