自定义QItemDelegate实现带CheckBox复选框的自增ID表格列

查找并参阅了多位前辈的文章,最后总结如下:


新建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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值