Draw on QTreeWidget With QPainter

981 views Asked by At

I'm working on a little program and I have a bunch of panels in it. I want it so that when I focus into a panel, it draws a thin inline around it to show that it is focused. I got it working with all my panels except my tree view.

Here's an example that works with a QWidget:

void Test::paintEvent(QPaintEvent *event)
{
    if(hasFocus())
    {
        QPainter painter(this);

        QPen pen(Qt::blue);
        pen.setWidth(1);
        painter.setPen(pen);

        painter.drawRect(geometry());

    }

    QWidget::paintEvent(event);
}

When I use the QPainter on the QTreeWidget I get these debug messages in the console:

  • QWidget::paintEngine: Should no longer be called
  • QPainter::begin: Paint device returned engine == 0, type: 1
  • QPainter::setPen: Painter not active
  • QPainter::drawRects: Painter not active

So my problem is that I can't use QPainter with the QTreeWidget so I am unable to draw my outline. Is there an alternative method I can use?

1

There are 1 answers

0
Jablonski On BEST ANSWER

You don't need paintEvent at all. Use just stylesheet (setStyleSheet() method):

QTreeWidget:focus{ border: 1px solid red}
QTreeWidget:!focus{}

Result:

enter image description here