Qt QTableView在活动单元格周围绘制边框 [英] Qt QTableView draw border around active cells

查看:965
本文介绍了Qt QTableView在活动单元格周围绘制边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在QTableView中实现类似于Excel的行为,其中在整个当前选择周围绘制边框.我已经尝试过这种感觉,感觉上有一百种不同的方式,并且不断遇到问题.我可以很容易地绘制边框,但是只要更改选择,边框的剩余部分就会留下.这是我在QTableView :: paintEvent中尝试过的一个示例...

I'm trying to implement behavior similar Excel in a QTableView, where a border is painted around the entire current selection. I have tried this what feels like a hundred different ways and keep getting problems. I can draw the border easily enough, but remnants of the border are left whenever the selection changes. Here is one example I've tried in QTableView::paintEvent ...


void MyTableView::paintEvent(QPaintEvent* event)
{
    // call QTableView's paint event first so we can draw over it
    QTableView::paintEvent(event);

    // activeSelection is a list of indexes that is updated in another function
    // the function also calls QTableView::repaint whenever this list changes
    // in an attempt to erase the previously drawn border
    if(!activeSelection.size())
        return;

    QRect rect = visualRect(activeSelection.at(0)) |
           visualRect(activeSelection.at(activeSelection.size() - 1));
    // temporarily draw smaller border so it doesn't lie on the grid lines
    rect.adjust(4, 4, -4, -4);
    QPen pen(Qt::black, 2);
    QPainter painter(viewport());
    painter.setPen(pen);
    painter.drawRect(rect);
}

该代码产生的结果例如

That code produces results such as this

关于如何使此运行更平稳的任何建议,我都希望得到.我曾尝试在委托中执行此操作,但是委托需要了解所有选定的索引,并且它无法在由QTableView绘制的网格线上绘制.另外,我的表类需要知道边界的绘制位置.

I would love any suggestions on how to make this run more smoothly. I had tried doing this in the delegate, but then the delegate needs to know all the indexes that are selected and it can't paint over the grid lines drawn by the QTableView. Plus, my table class needs to know where the border has been drawn.

推荐答案

尝试调用update();在您的selectionChanged函数中.这会减慢您的执行速度,但会删除垃圾.

try to call update(); in your selectionChanged function. this will slow out your implementation, but will remove garbage.

这篇关于Qt QTableView在活动单元格周围绘制边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆