1
votes

I spent last night trying to get this QScrollArea to work without any luck. What I am trying to do is to add a top horizontal menu layout and a scrollable vertical content layout beneath the menu. The scrollbar is not visible and the content layout pops out of place as soon as I add new elements to it (by click one of the menu buttons).

Please help me out. :)

Regards, Lars Erik

import sys 
from PyQt4 import QtCore, QtGui, Qt 

class MainWindow( QtGui.QMainWindow ): 

    def __init__( self ): 

        QtGui.QMainWindow.__init__( self ) 

        self.centralWidget = QtGui.QWidget() 
        self.setCentralWidget( self.centralWidget ) 

        #Main Layout 
        layout = QtGui.QVBoxLayout() 
        layout.setSpacing( 0 )         
        self.centralWidget.setLayout( layout ) 

        #Top Menu Layout 
        hLayout = QtGui.QHBoxLayout() 
        layout.addLayout( hLayout ) 

        i = 0 
        while i < 5: 
            addContent = QtGui.QPushButton( 'Add Content' ) 
            hLayout.addWidget( addContent ) 

            self.connect(addContent, QtCore.SIGNAL('clicked()'), self.addContent)             
            i += 1 

        #Content Layout 
        self.lowerWidget = QtGui.QWidget() 
        #self.lowerWidget.setMaximumSize( Qt.QSize(150, 250) ) 

        self.scrollArea = QtGui.QScrollArea() 
        self.scrollArea.setWidget( self.lowerWidget )           

        layout.addWidget( self.lowerWidget )   

        self.vLayout = QtGui.QVBoxLayout() 
        self.lowerWidget.setLayout( self.vLayout ) 

        i = 0 
        while i < 25: 
            label = QtGui.QLabel( 'Content' ) 
            self.vLayout.addWidget( label ) 
            i += 1             


    def addContent(self): 

        label = QtGui.QLabel( 'Content' ) 
        self.vLayout.addWidget( label ) 


if __name__ == '__main__': 

    app = QtGui.QApplication(sys.argv) 
    mainWin = MainWindow() 
    mainWin.show() 
    sys.exit(app.exec_())
1
Adding self.vLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize) will fix the popping-out problem, but I have no idea about the scrollbars.li.davidm
Your example, plus the answer above, helped me get a QScrollArea with a Layout inside of it, so, THANKS! I'd been messing with this all night.WhyNotHugo

1 Answers

3
votes

This looks wrong:

self.scrollArea = QtGui.QScrollArea() 
self.scrollArea.setWidget( self.lowerWidget )           

layout.addWidget( self.lowerWidget )

You add lowerWidget to the scrollarea, just to add it to the layout in the next step, which removes lowerWidget from the scrollarea and reparent its top level widget. You must add the scrollarea to the layout:

self.scrollArea = QtGui.QScrollArea() 
self.scrollArea.setWidget( self.lowerWidget )       

layout.addWidget( self.scrollArea )