[PyQt] QTreeView (and QTreeWidget) horizontal scroll bar jumping

Doug Bell dougb at bellz.org
Mon Apr 7 03:21:46 BST 2014

Thomi Richards wrote:
> Hi,
> I have an application with a tree view that has a rather large tree inside
> it. I've tweaked the tree view header so the tree view's horizontal
> scrollbar works as I'd like, as documented here:
> http://qt-project.org/faq/answer/how_can_i_ensure_that_a_horizontal_scrollbar_and_not_an_ellipse_shows_up_wh
> However, I notice that when I use the arrow keys to navigate a tree view,
> every time I press the "Down" arrow on the keyboard to select a new tree
> view item, the horizontal scrollbar resets itself to show the
> left-hand-most content in the view.
> I have a minimal example that shows the problem:
> http://paste.ubuntu.com/7214797/
> Run it, expand the tree with the arrow keys till it's off the right-hand
> edge of the window. Move the scrollbar to the right, and try moving around
> with the keyboard.
> Ideally, the horizontal scrollbar would move left/right to keep the
> currently selected item's text in view.
> Does anyone know if this can be achieved? I imagine I'd need to override or
> set something in QAbstractItemView, but the documentation for that class
> seems rather opaque to me.

I fixed this problem in my TreeLine program by overriding the
QTreeView::scrollTo method as shown below:

   def scrollTo(self, index, hint=QtGui.QAbstractItemView.EnsureVisible):
        """Scroll the view to make the node at index visible.

        Overriden to stop autoScroll from horizontally jumping when selecting
            index -- the node to be made visible
            hint -- where the visible item should be
        horizPos = self.horizontalScrollBar().value()
        super().scrollTo(index, hint)


More information about the PyQt mailing list