ChaniBlog











{November 25, 2012}   QHeaderView, ResizeToContents and stretchLastSection

I’m using a lot of QTreeViews at work. So many damn QTreeViews. :P One of the problems I ran into was that QHeaderView::ResizeToContents and QHeaderView::Stretch are mutually exclusive. I had my own custom RichTextDelegate (not Andre’s RichTextDelegate, it wasn’t quite what I wanted) as the only column of a treeview, and I wanted a scrollbar when the contents didn’t fit, but I didn’t want the column to shrink smaller than the view because that looks goofy (especially with alternatingRowColors on mac).

You can’t just setStretchLastSection(), because that just changes the resizeMode from ResizeToContents to Stretch and you lose your scrollbar. QHeaderView’s resize modes are all mutually exclusive, which is a real shame (especially if you wanted them user-resizable, but thankfully I don’t).

I made an attempt to tackle this problem again on friday, not really expecting to make progress. It turned out sandsmark was trying to solve the same problem too – he was thinking of subclassing QHeaderView, and I was hoping I could just subclass QTreeView (which I was going to need to do for some moveCommand stuff anyways). Surprisingly, I could. :)

It turns out QHeaderView relies a lot on its view’s sizeHintForColumn(). So, after subclassing the view, I just reimplemented that function and had it never return a width smaller than the view’s width:


int CustomTreeView::sizeHintForColumn(int column) const
{
int viewSize = viewport()->width();
int colSize = QTreeView::sizeHintForColumn(column);
return qMax(viewSize, colSize);
}

(damnit wordpress, why doesn’t the <code> tag let me indent easily?)

of course it’ll get more complicated if you have more columns, but when it’s just a one-column tree, this is a really nice trick. :)

[edit: wow, this is my 300th post. hard to believe I've written that much in.. what, 6 years?]



et cetera
Follow

Get every new post delivered to your Inbox.

Join 360 other followers

%d bloggers like this: