查找并参阅了多位前辈的文章,最后总结如下:
新建C++类继承QItemDelegate,并覆写如下三个函数:
//绘制背景及内容、样式
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
//创建编辑控件
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
//鼠标、键盘事件处理
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
1、绘制自增的编号/行号及复选框
void MyAutoIndexColumnDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem myOption = option;
//绘制背景(默认蓝色底),不写这句的话,复选框背景无法显示高亮状态
drawBackground(painter, myOption,index);
//绘制复选框,并根据index的Qt::CheckStateRole值改变状态
QRect r(myOption.rect.left()+3,myOption.rect.top()+myOption.rect.height()/2-8,16,16);
Qt::CheckState checkstate=static_cast<Qt::CheckState>(index.data(Qt::CheckStateRole).toInt());
drawCheck(painter, myOption,r,checkstate);
//序号居中显示,绘制时向右偏移一个值来避开Checkbox
QRect r1(r.right()+3,myOption.rect.top(),myOption.rect.width()-20,myOption.rect.height());
myOption.displayAlignment = Qt::AlignHCenter | Qt::AlignVCenter;
//绘制文本
drawDisplay(painter, myOption, r1,QString(" ")+ QString::number(index.row()+1));
//如果当前有焦点,就绘制一个焦点矩形,否则什么都不做
drawFocus(painter, myOption, myOption.rect);
}
2、设置动作
bool MyAutoIndexColumnDelegate::editorEvent(QEvent *event,QAbstractItemModel *model,const QStyleOptionViewItem &option,onst QModelIndex &index)
{
if(event->type() == QEvent::KeyPress)
return false;
if(event->type() == QEvent::MouseButtonRelease)
{
QMouseEvent *mouse_event = static_cast<QMouseEvent*>(event);
//只有左键点击才有效
if(mouse_event->button() != Qt::LeftButton)
{
return false;
}
// QRect r(option.rect.left(),option.rect.top(),20,20);
// //直接点击复选框时才更改状态
// if(!r.contains(mouse_event->pos()));
// {
// return false;
// }
//根据当前单元格的选中状态来在 选中/未选中 之间切换
QVariant value = index.data(Qt::CheckStateRole);
Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked
? Qt::Unchecked : Qt::Checked);
//设置当前单元格的选中状态
bool ok=model->setData(index,state, Qt::CheckStateRole);
return ok;
}
}
3、设置列内容不可编辑
QWidget *MyAutoIndexColumnDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,const QModelIndex &index) const
{
return NULL;
}