pythonpyqtscrollbarqscrollarea

PyQt: How to create a scrollable window


I think it should be much easier to create a scrollable window in PyQt. I have a list of labels that goes out of the window and I would like to scroll down to view them. At the moment the code does not give me an error, but the window just doesn't appear:

class Example(QWidget):

    def __init__(self):
        super().__init__()

        layout = QVBoxLayout()

        lbl_arr = makeLabelArr()

        for i in range(1,8):
            qb = lbl_arr[i]
            # qb.setFixedWidth(300)
            layout.addWidget(qb)

        layout.setAlignment(Qt.AlignTop)

        scroll = QScrollArea()
        scroll.setWidget(self)
        scroll.setWidgetResizable(True)
        scroll.setFixedHeight(400)

        layout.addWidget(scroll)

        self.setLayout(layout)


        self.setGeometry(0, 0, 600, 220)
        self.setWindowTitle('SnP watchlist')

        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    #print(QDesktopWidget().availableGeometry())

    ex = Example()
    sys.exit(app.exec_())

Solution

  • Make the window itself a QScrollArea, like this:

    class Window(QScrollArea):
        def __init__(self):
            super(Window, self).__init__()
            widget = QWidget()
            layout = QVBoxLayout(widget)
            layout.setAlignment(Qt.AlignTop)
            for index in range(100):
                layout.addWidget(QLabel('Label %02d' % index))
            self.setWidget(widget)
            self.setWidgetResizable(True)