PyQt QScrollArea not scrolling

2019-02-28 10:08发布

I want to put some elements of my UI in a scroll area as there can be a lot of them. I tried the following peice of code, but the area just keeps growing as I put more elements on it.

In the first part I set up a scroll area, a widget and a layout. I apply the layout to the widget and I set the widget to the scrollarea. Then I fill in my layout in an external function. The button under all of it allows to fill more elements in the layout.

    scrollRow = QtGui.QScrollArea()
    scrollRow.setMaximumSize(600, 400)
    self.rowAssetWidget = QtGui.QWidget()
    self.rowAssetLayout = QtGui.QGridLayout()
    self.rowAssetLayout.setSpacing(20)
    self.rowAssetWidget.setLayout(self.rowAssetLayout)
    scrollRow.setWidget(self.rowAssetWidget)
    #self.mainLayout.addLayout(self.rowAssetLayout, 2, 0)
    self.mainLayout.addWidget(self.rowAssetWidget, 2, 0)
    self.assetRow()

    self.addAssetRowBtn = QtGui.QPushButton("+")
    self.addAssetRowBtn.setFixedSize(20, 20)
    self.mainLayout.addWidget(self.addAssetRowBtn, 3, 0)
    self.connect(self.addAssetRowBtn, QtCore.SIGNAL("clicked()"), self.addAssetRow)

My elements appear fine, but it is not scrolling. Any idea ?

1条回答
男人必须洒脱
2楼-- · 2019-02-28 11:03
import sys
from PyQt4 import QtGui,QtCore
class LayoutTest(QtGui.QWidget):
    def __init__(self):
        super(LayoutTest, self).__init__()
        self.horizontalLayout = QtGui.QVBoxLayout(self)
        self.scrollArea = QtGui.QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollAreaWidgetContents = QtGui.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 380, 280))
        self.horizontalLayout_2 = QtGui.QHBoxLayout(self.scrollAreaWidgetContents)
        self.gridLayout = QtGui.QGridLayout()
        self.horizontalLayout_2.addLayout(self.gridLayout)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.add_button = QtGui.QPushButton("Add Items")
        self.horizontalLayout.addWidget(self.scrollArea)
        self.horizontalLayout.addWidget(self.add_button)
        self.connect(self.add_button, QtCore.SIGNAL("clicked()"), self.addButtons)
        self.setGeometry(300, 200, 400, 300)

    def addButtons(self):
        for i in range(0, 50):
            self.r_button = QtGui.QPushButton("Button %s " % i)
            self.gridLayout.addWidget(self.r_button)
def run():

    app = QtGui.QApplication(sys.argv)
    ex = LayoutTest()
    ex.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    run()

I know its too late to answer for this question, but here is a working example and you missing the parent layout.

查看更多
登录 后发表回答