python - 无法动态地将小部件添加到 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()
解决方案
您需要您的滚动区域能够针对动态添加的小部件进行自我调整
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)
推荐阅读
- javascript - click on a button - bind a click function to another one
- angularjs - AngularJS - 如何根据特定的 JSON 属性设置 Select 值?
- django - messages.error() 格式不正确,但 .success() 可以
- ios - Obj-C - Xcode 控制台中的 TIC 读取状态?
- mysql - 基于变量值的sql查询,需要忽略空变量,考虑包含值的变量
- r - doMPI 和节点、处理器和内核
- javascript - 使用 iOS 应用嵌入 AngularJS web 时有没有更好的调试和开发方法
- node.js - ArangoDB:从运行 Arango 的同一服务器连接时出现登录问题
- android - 数组列表过滤器?
- logrotate - 如何使 logrotate 为已经存在的日志文件工作?