PDA

View Full Version : QListWidget - pin item / scroll position during resizing



t_3
7th February 2015, 16:01
i have a QListWidget which shows a larger number of fixed sized icons; by clicking an icon, a preview is shown directly above the list widget, thus causing it to move and resize (vertically). what i wanted to achieve is to keep the clicked item exactly where it was (= relative to the click position), but with a general solution = not based on calculations from the item's position and/or cursor position.

since the solution probably also works for other situations where the scroll/item position should be pinned when the widget resizes, i thought i'd post it here. it's actually pretty simple, but still took me a while to figure it out ;)


void MyListWidgetView::resizeEvent(QResizeEvent *event)
{
int prevScollVal = verticalScrollBar()->value(); // the scrollbar value needs to be taken before resizing occurs!
int scrollOffset = event->size().height() - event->oldSize().height();

QListWidget::resizeEvent(event);

verticalScrollBar()->setValue(prevScollVal - scrollOffset);
// in order to avoid visible jumping of the list view, the scrollbar value should be set after passing the event!
}