QTableView实现行选和复选框

');" >
其中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);
}
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值