sgfw
sgfw

Reputation: 312

How can I replicate this tkinter scroll behavior with pyQT?

What I'm trying to do is get a scrolling view of n elements stacked on top of each other, and when they are not big enough to warrant an active scroll bar, they are pushed to the top. (So far I've managed to get similar behavior with pyQT, but the elements expand to fit the window, which I do not want. Here are some images of what I am trying to replicate:

When there is one element (two including the button), it is pushed to the top

One element

When there are more elements, it is still all pushed to the top

Multiple elements

And when the elements stack is too tall to fit on the screen, the scroll bar becomes active

Many elements

Does anyone know how I can do this in pyQT? I can provide additional infrmation if needed. Thanks

Upvotes: 1

Views: 84

Answers (1)

ekhumoro
ekhumoro

Reputation: 120678

You need to put the widgets in a vertical layout, and then add an expandable spacer at the bottom:

from PyQt4 import QtCore, QtGui

class Window(QtGui.QScrollArea):
    def __init__(self):
        super(Window, self).__init__()
        self.setWidgetResizable(True)
        widget = QtGui.QWidget(self)
        layout = QtGui.QVBoxLayout(widget)
        for text in 'One Two Three Four Five Six Seven'.split():
            button = QtGui.QPushButton(text)
            layout.addWidget(button)
        layout.addStretch()
        self.setWidget(widget)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 300, 200)
    window.show()
    sys.exit(app.exec_())

Upvotes: 1

Related Questions