注意模型索引转换××××××××

##建立模型数据

数据成员

  custommodel =new CustomModel();

  customproxymodel = new CustomProxyModel;

       customproxymodel->setSourceModel(custommodel);

      customtable= new CustomTable(this);

     customtable->setModel(customproxymodel);

  *设置数据时先setmodel(null)

   customtable->setModel(NULL);

   customproxymodel->setSourceModel(NULL);

 

//向 custommodel 中添加数据记录............

//设置模型

  customproxymodel->setSourceModel(custommodel);

customtable->setModel(customproxymodel);

 ##过滤行

#1 按指定行,列过滤表格

 a:过滤行重载filterAcceptsRow(int source_row,const QModelIndex & source_parent)const 虚函数 返回true 显示符合条件的行 ;false 不显示符合条件的行

{

  if(m_filterflag)

  {

    QModelIndex index1=sourceModel()->index(source_row,0,source_parent); //注意source_row 是指在源模型中的行号,0:过滤时按那列的元素进行过滤

    if(index1.row()!=2)return true;//当第2行时 过滤掉 不显示

      return false;

  }

  return true;

}

b:过滤列重载filterAcceptsColumn(int source_column,const QModelIndex & source_parent)const 虚函数

{

  if(m_filterflag)//是否过滤标识

  {

    QModelIndex index1=sourceModel()->index(4,source_column,source_parent); //注意source_columnw 是指在源模型中的列索引,4:过滤时按那行的元素进行过滤

    if(index1.column()!=1)return true;//当第1行时 过滤掉 不显示

      return false;

  }

  return true;

}

3:刷新表格过滤 添加公共函数调用QsortFilterProxyModel的invalidateFilter()接口

costomproxy::setFilterFlag(bool flag)

{

  m_filterflag = flag;

}

costomproxy::filterflag(){return m_filterflag;}

costomproxy::invalidateModel()

{

  invalidateFilter()

}

4:调用刷新表格

bool flag  = m_proxyModel->filterflag();

m_proxyModel->setFilterFlag(!flag);

m_proxyModel->invalidateModel();

##排序

a重载QSortFilterProxyModel::lessThan 函数(const QModelIndex& left,const QModelIndex& right)const

*注意QModelIndex的换算

{ //按第三列排序

bool ok1,ok2;

 QModelIndex leftIdx,rightidx;

leftidx=left.model()->index(left.row(),3,left.parent());

rightidx=rightidx.model()->index(right.row(),3,right.parent());

int l =left.data().toString().toInt(&ok1);

int r= right.data().toString().toInt(&ok2);

retur l<r;

 

}

b:调用方法

调用

customtable->setSortingEnabled(true);

或者

customproxymodel->sort(1,Qt::DescendingOrder);

 

 参考1: https://blog.csdn.net/qq78442761/article/details/84875123?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

2:https://blog.csdn.net/wjs1033/article/details/50732393

 

  

 

posted on 2020-07-30 11:21  keleman  阅读(1374)  评论(0编辑  收藏  举报