PDA

View Full Version : Center icon in QListView using QStyledItemDelegate



franki
10th June 2013, 20:56
Hi all

I'm struggling with QListView and subclassed QStyledItemDelegate
Basically, I have QListView in left frame of my app, and there are icons with description below.
Problem is that when I resize my app icons are aligned to left, and I would like them to be aligned to center.
So this is what I did:
1. I subclassed QListView so it sends signal with new size from resizeEvent function
2. I subclassed QStyledItemDelegate and I'm painting item in paint function

Problem is:
When I resize my app, and last items from QListView goes out of visible area, Vertical scrollBar should appear, but then there is some loop, scrollbar appears and disappears in loop, QListView is blinking with scrollbar, and resizeEvent is generated for QListView, over and over again, one event with slightly lower width and next one with slightly bigger width, just as scrollbar disappears and appears.
How to avoid this loop?
When I set policy for scrollbar alwaysOn then it works as it should.

I'm developing on Linux with Qt 4.8.2

Best Regards
Marek

franki
11th June 2013, 09:53
Well,

I will reply to myself, it was my fault ;)
When I stretched left frame, I also set new sizes for individual items with:
leftFrameModel->item(i,0)->setSizeHint(QSize(size.width(),size.width()));
(QSize size - is size of QListView as reported from resizeEvent inside QListView)

Thus items grew both in width and height (like a square) when QListView was stretched, until there was no more space in height to accommodate all items. When vertical scroll bar appears it takes some space previously used for items placed in this QListView, consequently QListView reports that its width shrank a bit (due to scroll bar width), this signal is send to my function which sets proper size for QListView items as mentioned before. Because QListView after QScrollBar appeared has less width, my function sets size for all items inside QListView according to that new QSize, but because items are rendered as squares, height of the items is also a bit smaller. With new sizes set for all items (slightly smaller with scrollbar than without) sum of height of all items is less than height of QListView, so scroll bar is not needed anymore ;) so scroll bar disappears and QListView resizes itself, QListView is again a bit wider, signal is send to my function that again sets all items width and height according to that new slightly bigger width, and this slightly bigger width causes that sum of height of all items is more than QListView height, so scroll bars appears again, and we have infinite loop.

Solution: When I resize QListView items during stretching QListView I don't alter their height, only width, so they are not squares any more, but icon is centered and it looks good, more important sum of height of all items is the same with or without vertical scrollbar.

Cheers
Marek