Search code examples
resizepyqtpyqt4qscrollarea

Set QScrollbar width to prevent the need for horizontal scrollbar


Is there a way to set the width of a QScrollArea so that a horizontal scrollbar is not needed? I know I can hide horizontal scrollbar by setting it's policy to always off. However, I want to make the QScrollArea large enough to not need it.

I'm currently somewhat doing this by using scrollbar.setFixedWidth(). Is there a better way, with something like scrollbar.setSizetoContents() or something similar?

As a side note, what is the best way to get the maximum width of all the widgets in a layout anyway?


Solution

  • I finally figured it out. Here is the hackish code I was using to find out the width of one of my sub-widgets in the scrollarea:

    def _restrictWidthToFit(self):
        layout = self._scroll.widget().layout()
        if layout.count() > 0:
            fw = layout.itemAt(0).widget().sizeHint().width()
            sw = self._scroll.verticalScrollBar().sizeHint().width()
            w = fw + sw
            return w
    

    The trick was I was previously setting this width when first adding the widgets into the scrollarea. However, the sizes aren't completely filled out by Qt at this point apparently. Thus, I used the above method to set the width by overriding the showEvent():

    def showEvent(self, ev):
        super(UIFilterCollection, self).showEvent(ev)
        self._scroll.setFixedWidth(self._restrictWidthToFit())
    

    At this point the width is filled out so it seems to work.

    It's also worth noting that all of my sub-widgets are the same width already since they are in a