How to add to QVBoxLayout after it was associated with a QScrollArea ?
Solved
Qt for Python
-
I would like to add widgets to a QVBoxLayout sometime later in my code after some user interaction.
The existing code I have works fine if I add widgets to my layout before I perform the QScrollArea but if I were to add them after that, it does not show up. In addition to addWidget() is there some other calls I need to make to tell Qt that the QVBoxLayout content has been updated ?
import sys from PySide2 import QtWidgets, QtCore class Example(QtWidgets.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): before = False scroll = QtWidgets.QScrollArea(self) vbox = QtWidgets.QVBoxLayout() if before: for index in range(20): vbox.addWidget(QtWidgets.QPushButton('button {}'.format(index))) widget = QtWidgets.QWidget() widget.setLayout(vbox) scroll.setWidget(widget) if not before: for index in range(20): layout = widget.layout() layout.addWidget(QtWidgets.QPushButton('button {}'.format(index))) self.setGeometry(300, 300, 300, 150) self.setWindowTitle('Buttons') def main(): app = QtWidgets.QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
-
Answering my own question.
I need to make the scroll resizable, i.e.
scroll = QtWidgets.QScrollArea(self) scroll.setWidgetResizable(True)
Cheers
-
@nicholas_yue
Without understanding why, I, and most others, always setsetWidgetResizable(True)
! I'm sure there are cases where one does not want to do this, especially since it defaults to false, but I don't know what they are. :)