2013-12-21 36 views
2

對於pyside來說非常新穎,所以也許是一個愚蠢的問題。我想創建一個pyside UI,其中包含可變數量的項目,並且還可以在項目運行時添加項目,並且使其更加複雜,還需要滾動條以將其全部放在屏幕上!在pyside上添加小部件

這是我有現在:

import sys 

from PySide import QtGui 
from PySide import QtCore 
class example(QtGui.QWidget): 

    def __init__(self, parent= None): 
     super(example, self).__init__() 

     grid = QtGui.QGridLayout() 
     grid.setSpacing(10) 

     self.widget = QtGui.QWidget() 

     self.layout = QtGui.QGridLayout(self) 

     for i in range(5): 
      btn = QtGui.QPushButton("test"+str(i)) 
      self.layout.addWidget(btn,i,0) 
      btn.clicked.connect(self.buttonClicked) 
     self.count = i 
     self.widget.setLayout(self.layout) 


     self.scroll = QtGui.QScrollArea() 
     self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) 
     self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) 
     self.scroll.setWidget(self.widget) 

     grid.addWidget(self.scroll,3,0) 
     self.setLayout(grid) 


    def buttonClicked(self): 
     title = QtGui.QLabel('Title'+str(self.count)) 
     self.layout.addWidget(title,self.count + 1,0) 
     self.count += 1 
     self.widget.addLayout(self.layout,0) 
     self.scroll.addWidget(self.widget,0) 


if __name__ == '__main__': 
    app = QtGui.QApplication(sys.argv) 

    dialog = example() 
    dialog.show() 

    sys.exit(app.exec_()) 

但不知何故,通過一個按鈕添加項目時佈局被搞砸。

有沒有人有一個想法如何解決這個問題?

Thanx!

回答

4

你不遠處。你缺少的關鍵是QScrollArea.setWidgetResizable,這將確保Scrollarea自動調整其視口以適應內容。

我做了一些其他調整你的榜樣,並在適當情況下添加的註釋:

class example(QtGui.QWidget): 
    def __init__(self, parent= None): 
     super(example, self).__init__() 

     grid = QtGui.QGridLayout() 
     grid.setSpacing(10) 

     self.widget = QtGui.QWidget() 

     # set the widget as parent of its own layout 
     self.layout = QtGui.QGridLayout(self.widget) 

     for i in range(5): 
      btn = QtGui.QPushButton("test"+str(i)) 
      self.layout.addWidget(btn,i,0) 
      btn.clicked.connect(self.buttonClicked) 

     # following lines are redundant 
     # self.count = i 
     # self.widget.setLayout(self.layout) 

     self.scroll = QtGui.QScrollArea() 
     # need this so that scrollarea handles resizing 
     self.scroll.setWidgetResizable(True) 
     # these two lines may not be needed now 
     self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) 
     self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) 

     self.scroll.setWidget(self.widget) 

     grid.addWidget(self.scroll, 3, 0) 
     self.setLayout(grid) 

    def buttonClicked(self): 
     title = QtGui.QLabel('Title' + str(self.layout.count())) 
     self.layout.addWidget(title) 
     # following lines are redundant 
     # self.layout.addWidget(title, self.count + 1, 0) 
     # self.count += 1 
     # self.widget.addLayout(self.layout,0) 
     # self.scroll.addWidget(self.widget,0) 
+0

感謝名單這wroks太棒了! –

相關問題