2010-12-18 78 views
1

我昨晚花了一個小時,試圖讓QScrollArea在沒有任何運氣的情況下工作。我想要做的是在菜單下添加一個頂部水平菜單佈局和一個可滾動的垂直內容佈局。滾動條不可見,只要向其中添加新元素(通過單擊其中一個菜單按鈕),內容佈局就會彈出。Qscrollarea不顯示scollbar和佈局彈出

請幫我一把。 :)

問候, 拉爾斯埃裏克

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_()) 
+0

添加'self.vLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)'將解決彈出出的問題,但我不知道滾動條的想法。 – 2010-12-18 16:53:40

+0

你的例子,加上上面的答案,幫助我得到一個QScrollArea,裏面有一個Layout,所以,謝謝!我整晚都在搞這個。 – WhyNotHugo 2012-02-16 06:38:11

回答

3

這看起來錯:

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

layout.addWidget(self.lowerWidget) 

您添加lowerWidget到scrollarea,只是爲了在下一步驟,從而消除其添加到佈局來自scrollarea的lowerWidget並重新設置其頂級小部件。 您必須將scrollarea添加到佈局:

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

layout.addWidget(self.scrollArea) 
+0

非常感謝。可以相信我犯了這個錯誤。我還必須添加這個:self.scrollArea.setWidgetResizable(True)。我認爲這是默認的。 – pompel 2010-12-18 17:58:41

+0

非常感謝。可以相信我犯了這個錯誤。順便說一句...我也不得不補充 – pompel 2010-12-18 17:59:55