现在的位置: 首页 > 综合 > 正文

QTableView实现行选和复选框

2014年01月23日 ⁄ 综合 ⁄ 共 1579字 ⁄ 字号 评论关闭

');" >
其中SelectionBehavior设置成SelectRows行选
showGrid设置成false,不显示表格
sortingEnabled设置成true,支持排序。(据说这个功能需要实现sort方法或者使用ProxyModel,还没有具体实验)
-------------------
然后,自定义一个ListModel
对于第一列数据要能够支持CheckBox,要能够显示图标,要能够显示文本
对应的就要返回Qt::CheckStateRole、Qt::DecorationRole、Qt::DisplayRole相应的数据。
我的实现如下:
QVariant ListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();

ListItem *item = static_cast<ListItem*>(index.internalPointer());

if (index.column()==0)//请求第一列数据
{
switch(role)
{
case Qt::DisplayRole://返回标题
return item->caption();
case Qt::DecorationRole://返回图标
if (item->readed())
return readed;
else
return unRead;
case Qt::CheckStateRole: //返回单选框状态
if (item->readed()) //这里由于QCheckBox是三态的,不应该简单的返回true,false
return Qt::Checked;
else
return Qt::Unchecked;
default:
return QVariant();
}
}
if ((index.column()==1) && (role==Qt::DisplayRole))
return item->description();
return QVariant();
}
其次,光是有这些还不够,QTableView需要通过ListMode的flags方法知道某个单元格是不是需要绘制CheckBox,
我的flags方法实现如下:
Qt::ItemFlags ListModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
  return 0;
if (index.column()==0)//对于第一列设置标志位
  return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;
//CheckBox
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
最后,结合这两样应该就能够正常显示了,不过这个时候的单选框还只是个摆设,需要实现setData方法让复选框可用,我的setData方法实现如下:
bool ListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
  return false;

ListItem *item= static_cast<ListItem*>(index.internalPointer());
if ((index.column()==0)&&(role==Qt::CheckStateRole))
//CheckStateRole表示执行复选框状态的数据更新
{
  if (value == Qt::Checked)
  item->setReaded(true);
  else
  item->setReaded(false);
}
}

抱歉!评论已关闭.