import sys from PySide2.QtWidgets import * from PySide2.QtGui import QFont from PySide2 import QtCore font = QFont() font.setPointSize(20) class NewButton(QPushButton): def __init__(self, *args): super().__init__(*args) self.setFont(font) class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.v1 = QVBoxLayout() self.v2 = QVBoxLayout() self.v2.b1 = NewButton("按钮1") self.v2.b2 = NewButton("按钮2") self.v2.b1.clicked.connect(self.additem) self.v2.addWidget(self.v2.b1) self.v2.addWidget(self.v2.b2) self.additem() w = QWidget() w.setLayout(self.v1) area = QScrollArea() area.setWidget(w) # area.setLayout(self.v1) area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) # area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) area.setWidgetResizable(True) layout = QHBoxLayout() layout.addWidget(area) # layout.addLayout(self.v1) layout.addLayout(self.v2) self.setLayout(layout) def additem(self): self.v1.addWidget(NewButton("新的按钮")) if __name__ == '__main__': app = QApplication(sys.argv) form = Form() form.show() sys.exit(app.exec_())
思路说明
QScrollArea 只要简单设置就能有滚动条 QScrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
PS,水平方向有相似的方法,后面的参数不能是bool值,只能是QtCore.Qt.ScrollBarAlwaysOn或者QtCore.Qt.ScrollBarAlwaysOff
但是QScrollArea 不能和Layout一样addWidget或addLayout。QScrollArea实质还是Widget,只能setWidget或setLayout “挂载”上一个其他东西。
但实际测试发现,还有一个十分重要的设置QScrollArea.setWidgetResizable(True)必须有,所以代码是一个QScrollArea先setWidget一个Widget然后Widget再setLayout上QVBoxLayout
我的视频里面有实际的效果演示
https://www.bilibili.com/video/BV13u411v7hp