Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt QTableView draw border around active cells

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

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.

like image 623
buck Avatar asked Jun 29 '11 04:06

buck


1 Answers

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

like image 121
Raiv Avatar answered Nov 15 '22 08:11

Raiv