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

Qt Code:
  1. void MyListWidgetView::resizeEvent(QResizeEvent *event)
  2. {
  3. int prevScollVal = verticalScrollBar()->value(); // the scrollbar value needs to be taken before resizing occurs!
  4. int scrollOffset = event->size().height() - event->oldSize().height();
  5.  
  6. QListWidget::resizeEvent(event);
  7.  
  8. verticalScrollBar()->setValue(prevScollVal - scrollOffset);
  9. // in order to avoid visible jumping of the list view, the scrollbar value should be set after passing the event!
  10. }
To copy to clipboard, switch view to plain text mode