Python 无法将小部件动态添加到QScrollArea对象

Python 无法将小部件动态添加到QScrollArea对象,python,pyqt,pyqt5,pyside2,Python,Pyqt,Pyqt5,Pyside2,当我想向qscrollara对象动态添加一个小部件时,我遇到了两个问题。当我评论这一行时,我想添加的新小部件无法显示在屏幕上。此外,我发现我无法在屏幕上滚动该区域 非常感谢您的帮助 from PyQt5.QtWidgets import * class MyList(QScrollArea): def __init__(self): super().__init__() self._widget = QWidget() self._la

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

非常感谢您的帮助

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

您需要您的scrollarea能够为动态添加的小部件进行自我调整

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)

什么是MyWidget,它的代码在哪里?什么“无法在屏幕上显示”、小部件或滚动区域?你说的“有一个bug”是什么意思?
\u list
参数是什么?请更准确地说,让自己清楚,记住,如果你想展示一个例子,你必须确保两者都是。你是对的。非常感谢你的建议。我对我的问题进行了修改,使其更加精简和可重复。很抱歉,我的正式描述给您带来了不便,您能帮我解决一下吗?@musicamante