我有一个包含复选框列表的滚动区域。我希望此滚动区域调整为应用程序的大小。无法弄清楚如何做到这一点。任何建议,将不胜感激。我在其他帖子中遇到过这个问题但是没有找到解决方案,或者至少是我理解的解决方案。
from PyQt4 import QtGui, QtCore
class Screen3(QtGui.QWidget): # Screen to display data
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
# layout for check box container widget
chkBoxLayout = QtGui.QVBoxLayout(self)
# create list of checkboxes
self.checkboxes = []
numofCheckboxes = 30
for x in range(numofCheckboxes):
self.checkboxes.append(QtGui.QCheckBox('test'))
# add checkboxes to chkBoxLayout
for i, chkbox in enumerate(self.checkboxes):
chkbox.setChecked(True)
chkBoxLayout.addWidget(chkbox)
chkBoxLayout.addStretch(1)
chkBoxLayout.setMargin(0);
chkBoxLayout.setContentsMargins(0,0,0,0)
chkBoxLayout.setSpacing(0)
# checkbox container widget
widget = QtGui.QWidget()
widget.setStyleSheet(""".QWidget {background-color: rgb(255, 255, 255);}""")
widget.setLayout(chkBoxLayout)
# checkbox scroll area, gives scrollable view on widget
scroll = QtGui.QScrollArea()
scroll.setMinimumWidth(120)
scroll.setMinimumHeight(200) # would be better if resizable
scroll.setWidgetResizable(True)
scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
scroll.setWidget(widget)
self.samplePanel = QtGui.QVBoxLayout()
self.samplePanel.addWidget(scroll)
self.samplePanel.addStretch(1)
# horizontal layout
hbox = QtGui.QHBoxLayout()
hbox.addLayout(self.samplePanel)
hbox.addStretch(1)
self.setLayout(hbox)
self.resize(100, 500)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Screen = Screen3()
Screen.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
您必须将QScrollArea
添加到主布局,您不需要创建其他布局。
class Screen3(QtGui.QWidget): # Screen to display data
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
# layout for check box container widget
chkBoxLayout = QtGui.QVBoxLayout()
# create list of checkboxes
self.checkboxes = []
numofCheckboxes = 30
for x in range(numofCheckboxes):
self.checkboxes.append(QtGui.QCheckBox('test'))
# add checkboxes to chkBoxLayout
for i, chkbox in enumerate(self.checkboxes):
chkbox.setChecked(True)
chkBoxLayout.addWidget(chkbox)
chkBoxLayout.addStretch(1)
chkBoxLayout.setMargin(0);
chkBoxLayout.setContentsMargins(0,0,0,0)
chkBoxLayout.setSpacing(0)
# checkbox container widget
widget = QtGui.QWidget()
widget.setStyleSheet(""".QWidget {background-color: rgb(255, 255, 255);}""")
widget.setLayout(chkBoxLayout)
# checkbox scroll area, gives scrollable view on widget
scroll = QtGui.QScrollArea()
scroll.setMinimumWidth(120)
scroll.setMinimumHeight(200) # would be better if resizable
scroll.setWidgetResizable(True)
scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
scroll.setWidget(widget)
lay = QtGui.QVBoxLayout(self)
lay.addWidget(scroll)