本文主要是介绍派生QAbstractProxyModel小例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
派生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_OBJECTpublic:
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 DEBUGstatic QFile file("log.text");static QTextStream stream(&file);#endif
RevertProxyModel::RevertProxyModel(QObject *parent): QAbstractProxyModel(parent){vector.clear();#ifdef DEBUG
这篇关于派生QAbstractProxyModel小例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!