首页 > 解决方案 > 无法动态地将小部件添加到 QScrollArea 对象

问题描述

当我想QScrollArea动态地将小部件添加到对象时,我遇到了两个问题。当我评论该行时,我想添加的新小部件无法显示在屏幕上。此外,我发现我无法滚动屏幕上的那个区域。

非常感谢您的帮助!

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()    

标签: pythonpyqtpyqt5pyside2

解决方案


您需要您的滚动区域能够针对动态添加的小部件进行自我调整

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)

推荐阅读