PDA

View Full Version : Paint a border around a QTreeWidget



m0nq1
8th January 2016, 17:03
Hello, I'm trying to paint a border around QTreeWidget. This QTreeWidget has only one column, and it is intended to look similar to this:

https://lh3.googleusercontent.com/-ivHUhvvlbGs/Vo_p1pKVgnI/AAAAAAAA6RA/H493iv4rWpY/s0/2016-01-08_17-54-43.png

That is, I am using it just to paint a hierarchy, not to have a spreadsheet-like widget. There are no column headers but, unlike that screenshot, the only column is supposed to always have a width of 100%.

For such matter I'm using qDrawShadePanel inside the paintEvent of the QTreeWidget. It is roughly like this:


void
MyQTreeWidget::paintEvent(QPaintEvent *event)
{
QPainter *p = new QPainter(viewport());
qDrawShadePanel(p, 0, 0, viewport()->width(), viewport()->height(), palette(), true, 1, NULL);
delete p;

QTreeWidget::paintEvent(event);
}

I also have a custom item delegate with a sizeHint() that paints a coloured background for each item and its text using a QPainter inside its paint() function. This coloured background spans the whole column.

Even though it all mostly works, I have a problem: the background I paint for each item overlaps the border. Inside the paint() function of the delegates, I have used adjust() on the QStyleOptionViewItem's QRect to remove one pixel from the left side and another pixel from the right side of the delegates before I use p->fillRect(rect) to draw the background of each delegate, but that's not an actual solution, because I can't do the same for the top and the bottom (the items would be separated one pixel from one another).

I expected setContentsMargins(1, 1, 1, 1) on the QTreeWidget to do what I want, but it doesn't work.

Any ideas? Thanks :)

ars
8th January 2016, 18:05
Hello,

Have you tried setting QTreeWidget FrameShape and FrameShadow?
QTreeWidget is derived from QFrame, so you can use
ui->myTreeWidget->setFrameShape(QFrame::Box);
ui->myTreeWidget->setFrameShadow(QFrame::Plain);
to set the frame around your widget. Using these two functions (or specifying the corresponding attributes in designer) there is no need for overriding the paint event in your derived TreeWidget class.

Best regards
ars

m0nq1
8th January 2016, 19:07
Thank you very much ars. I had tried this, or so I thought, but I didn't like the result. Now I tried it again and it's what I was looking for. Well, what can I say.

Greetings.