设置QAbstractTableModel的flags()函数,通过重写setData()与data()来实现。
下面就介绍最常用的方式,即方法二。
QMap用来保存选中行号以及对应的选中状态
QMap check_state_map;
setData()方法主要用来设置是否被选中,然后将对应的状态保存到QMap中
bool TableModel::setData( const QModelIndex &index, const QVariant &value, int role )
{
if(!index.isValid())
return false;
if (role == Qt::CheckStateRole && index.column() == 0)
{
check_state_map[index.row()] = (value == Qt::Checked ? Qt::Checked : Qt::Unchecked);
}
return true;
}
data()方法主要用来显示,取出QMap中的值,返回对应的状态
QVariant TableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
switch(role)
{
//case Qt::TextAlignmentRole:
// return Qt::AlignLeft | Qt::AlignVCenter;
//case Qt::DisplayRole:
// return arr_row_list->at(index.row()).at(index.column());
case Qt::CheckStateRole:
if(index.column() == 0)
{
if (check_state_map.contains(index.row()))
return check_state_map[index.row()] == Qt::Checked ? Qt::Checked : Qt::Unchecked;
return Qt::Unchecked;
}
default:
return QVariant();
}
return QVariant();
}
flag()方法主要设置用户可选角色,绘制出QCheckBox
Qt::ItemFlags TableModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
if (index.column() == 0)
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
效果如下: