PyQt:如何使小部件可滚动

16

我尝试让我的QGroupBox在高度超过400像素时可滚动。 QGroupBox中的内容是使用for循环生成的,以下是一个示例:

mygroupbox = QtGui.QGroupBox('this is my groupbox')
myform = QtGui.QFormLayout()
labellist = []
combolist = []
for i in range(val):
    labellist.append(QtGui.QLabel('mylabel'))
    combolist.append(QtGui.QComboBox())
    myform.addRow(labellist[i],combolist[i])
mygroupbox.setLayout(myform)

由于val的值取决于其他因素,无法确定myform布局的大小。为了解决这个问题,我添加了一个类似于QScrollableArea的内容:
scroll = QtGui.QScrollableArea()
scroll.setWidget(mygroupbox)
scroll.setWidgetResizable(True)
scroll.setFixedHeight(400)

不幸的是,这似乎对groupbox没有任何影响:没有滚动条的迹象。我错过了什么吗?

1个回答

24

除了明显的打字错误(我相信您想说的是QScrollArea),我看不出您发布的内容有什么问题。所以问题必须在代码中的其他地方:可能是缺少布局?为了确保我们在同一页上,下面的最小脚本对我来说可以正常工作:

screenshot

PyQt5

from PyQt5 import QtWidgets

class Window(QtWidgets.QWidget):
    def __init__(self, val):
        super().__init__()
        mygroupbox = QtWidgets.QGroupBox('this is my groupbox')
        myform = QtWidgets.QFormLayout()
        labellist = []
        combolist = []
        for i in range(val):
            labellist.append(QtWidgets.QLabel('mylabel'))
            combolist.append(QtWidgets.QComboBox())
            myform.addRow(labellist[i],combolist[i])
        mygroupbox.setLayout(myform)
        scroll = QtWidgets.QScrollArea()
        scroll.setWidget(mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setFixedHeight(200)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(scroll)

if __name__ == '__main__':

    app = QtWidgets.QApplication(['Test'])
    window = Window(12)
    window.setGeometry(500, 300, 300, 200)
    window.show()
    app.exec_()

PyQt4

from PyQt4 import QtGui

class Window(QtGui.QWidget):
    def __init__(self, val):
        QtGui.QWidget.__init__(self)
        mygroupbox = QtGui.QGroupBox('this is my groupbox')
        myform = QtGui.QFormLayout()
        labellist = []
        combolist = []
        for i in range(val):
            labellist.append(QtGui.QLabel('mylabel'))
            combolist.append(QtGui.QComboBox())
            myform.addRow(labellist[i],combolist[i])
        mygroupbox.setLayout(myform)
        scroll = QtGui.QScrollArea()
        scroll.setWidget(mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setFixedHeight(200)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(scroll)

if __name__ == '__main__':

    app = QtGui.QApplication(['Test'])
    window = Window(12)
    window.setGeometry(500, 300, 300, 200)
    window.show()
    app.exec_()

谢谢。我找到了我的错误,我把 QGroupBox 放在最终布局里面,而不是放 QScrollArea。现在它正常工作了。 - Chris Aung
5
在学习PyQt5并尝试使用可滚动区域时,我遇到了这个问题。我意识到scroll.setWidgetResizable(True)对于使小部件实际出现在滚动区域中至关重要。希望这能帮助未来的任何人。 - LoneWanderer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接