首先设置QTableView的属性,如图:
[img]http://

[/img]
其中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,falsereturn 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);
}
}
========================================
最后附上我的代码和数据库,希望对大家有帮助。
源代码
QtRSSReader.rar (293 K) 下载次数:480 这也是我的RSS阅读器目前位置的所有代码,我才发现按QWidget为单位划分模块是个不错的想法,测试也很方便。这让我的RSS阅读器的代码不至于太混乱