Issue
I met two problems when I want to add a widget to a QScrollArea
object dynamically. When I comment that line, the new widget I want to add could not be displayed on the screen. Moreover, I found that I could not scroll that area on the screen.
Thank you very much for any help!
from PyQt5.QtWidgets import *
class MyList(QScrollArea):
def __init__(self):
super().__init__()
self._widget = QWidget()
self._layout = QVBoxLayout()
# If I comment this line, MyButton._add function will not work, and the screen will not display new widget.
self._layout.addWidget(QPushButton('test'))
# set layout and widget
self._widget.setLayout(self._layout)
self.setWidget(self._widget)
# display settings
self.setMinimumSize(1024, 540)
class MyButton(QPushButton):
def __init__(self, text, _list):
super().__init__(text=text)
self._list = _list
self.clicked.connect(self._add)
def _add(self):
self._list._layout.addWidget(QPushButton('test'))
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self._layout = QVBoxLayout()
self._my_list = MyList()
self._my_button = MyButton(text='Add', _list=self._my_list)
self._layout.addWidget(self._my_list)
self._layout.addWidget(self._my_button)
# set layout
self.setLayout(self._layout)
# display settings
self.setWindowTitle('My Demo')
def main():
app = QApplication([])
main_window = MainWindow()
main_window.show()
app.exec_()
if __name__ == "__main__":
main()
Solution
You need your scrollarea to be able to adjust itself for dynamically added widgets
class MyList(QScrollArea):
def __init__(self):
super().__init__()
self._widget = QWidget()
self._layout = QVBoxLayout()
# If I comment this line, MyButton._add function will not work, and the screen will not display new widget.
self._layout.addWidget(QPushButton('test'))
# set layout and widget
self._widget.setLayout(self._layout)
self.setWidget(self._widget)
# display settings
# self.setMinimumSize(1024, 540) remove this to get more dynamic behavior
# add this line
self.setWidgetResizable(True)
Answered By - T.sagiv
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.