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.
try to call update(); in your selectionChanged function. this will slow out your implementation, but will remove garbage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With