Qt QTableView draw border around active cells

妖精的绣舞 提交于 2019-12-07 03:22:38

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/6515695/qt-qtableview-draw-border-around-active-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!