QScrollArea不显示滚动条,布局位置错误

1 投票
1 回答
1553 浏览
提问于 2025-04-16 08:42

我昨晚花了很多时间想让这个QScrollArea正常工作,但一直没成功。我想做的是在顶部添加一个水平菜单布局,然后在菜单下面放一个可以上下滚动的内容布局。但是,滚动条看不见,而且一旦我点击菜单按钮添加新元素,内容布局就会跑到别的地方。

请帮帮我。 :)

谢谢, 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 个回答

3

这看起来不太对:

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

layout.addWidget( self.lowerWidget )

你把 lowerWidget 加到滚动区域里,但接下来又把它加到布局里,这样就把 lowerWidget 从滚动区域里移除了,并且把它的顶层小部件重新归属给了其他地方。你应该把滚动区域加到布局里:

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

layout.addWidget( self.scrollArea )

撰写回答