Search code examples
pythonpython-3.xpyqtpyqt5qscrollarea

Signal QscrollArea


I would like to know is it possible to have a signal or something to know when the scroll is available and when it is no longer available each time the window is resized?

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class Widget(QWidget):
    def __init__(self, parent= None):
        super(Widget, self).__init__()

        widget = QWidget()

        layout = QVBoxLayout(self)

        for _ in range(10):
            btn = QPushButton()
            layout.addWidget(btn)

        widget.setLayout(layout)

        scroll = QScrollArea()
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll.setWidget(widget)
        vLayout = QVBoxLayout(self)
        vLayout.addWidget(scroll)
        self.setLayout(vLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    dialog = Widget()
    dialog.show()
    app.exec_()

Solution

  • Since a QScrollBar is usually visible only when its range maximum is greater than 0, you can just check that value.

    class Widget(QWidget):
        def __init__(self, parent= None):
            # ....
            # note that the scroll area is now an instance member
            self.scroll = QScrollArea()
            self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
            self.scroll.setWidget(widget)
            self.scroll.verticalScrollBar().rangeChanged.connect(self.checkScrollBarRange)
            vLayout = QVBoxLayout(self)
            vLayout.addWidget(self.scroll)
            self.setLayout(vLayout)
    
            # the next is important when resizing the widget containing the scroll area
            self.scroll.installEventFilter(self)
    
        def eventFilter(self, source, event):
            if source == self.scroll and event.type() == QEvent.Resize:
                self.checkScrollBarRange()
            return super().eventFilter(source, event)
    
        def checkScrollBarRange(self):
            if (self.scroll.verticalScrollBarPolicy() != Qt.ScrollBarAlwaysOff and
                self.scroll.verticalScrollBar().maximum()):
                    print('vertical scroll bar IS visible')
            else:
                print('vertical scroll bar NOT visible')