pythonpyqt4qlistwidgetqscrollbar

How can I add a vertical scrollbar to a QListWidget()


I have a QListWidget which contains QListWidgetItems that exceed its visible boundaries and I would like to add a vertical Scrollbar. I have tried the following:

sz = QtCore.QSize(200,200)
_lstwdgt = QtGui.QListWidget(parent)
_item = QtGui.QListWidgetItem(_lstwdgt)
_widget = QtGui.QWidget(parent)
_layout = QtGui.QVBoxLayout()
for n in range(0,10):
    _btn = QtGui.QPushButton("test {}".format(n), parent)
    _layout.addWidget(_btn)
_layout.addStretch()
_layout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
_widget.setLayout(_layout)
_item.setSizeHint(_widget.sizeHint())
_lstwdgt.addItem(_item)
_lstwdgt.setItemWidget(_item,_widget)
_lstwdgt.setFixedSize(sz)
vScrollBar = QtGui.QScrollBar(_lstwdgt)
_lstwdgt.setVerticalScrollBar(vScrollBar)

but no vertical scrollbar becomes visible. When I change _layout to be QHBoxLayout() however, a horizontal scrollbar will appear, what is missing to get a vertical scrollbar instead?


Solution

  • The problem is that by default every view uses the ScrollPerItem scroll mode: with this mode, the scroll bar is only used to scroll between items, and since your view only has one item, Qt doesn't think it has to show the scroll bar.

    The solution is to change the mode to ScrollPerPixel:

    _lstwdgt.setVerticalScrollMode(QtGui.QListWidget.ScrollPerPixel)
    

    Note that if you only need to add widgets to a scrollable area, using a QListWidget is really a very bad idea, and a QScrollArea should be used instead.
    Also, adding a stretch is completely pointless since you're using the sizeHint for the item, and size hints only returns the minimal optimal size (which ignores any stretch, which are spacers that can be shrunk to 0 sizes).

    I also strongly suggest you to use more verbose variable names, there's really no benefit in abbreviating names like _lstwdgt (nor adding underscore prefixes for every object in a local scope); it took me more time to understand what your code did than to actually find the reason of your problem. Remember, readability is really important in programming.