2016-03-21 17 views
1

我寫了一個使用PyQt構建GUI的程序。從Qt Designer中,我有一個MainWindow,一個QTabWidget和QTabWidget中的一個QScrollArea。我試圖動態構建匹配數據匹配列表,將每個匹配添加到小部件的佈局,並將此佈局放置在QScrollArea中。目前,我的代碼做這個完美,但它提出了以下錯誤:用新的替換QScrollArea的佈局

QLayout: Attempting to add QLayout "" to MainWindow "MainWindow", which already has a layout 

這對我來說很有意義,但我不知道如何解決它。我甚至不確定我的所作所爲是如何做的,這使得它很難修復。在我的MainWindow __init__()方法中,我創建了一個MatchHistoryBuilder類(它構建了每個匹配項)的一個實例,調用了一個buildMatchHistory()方法(它在MainWindow類中),並將它的MatchHistoryBuilder實例傳遞給它,就像這樣的:

matchHistoryBuilder = MatchHistoryBuilder(self) 
self.buildMatchHistory(matchHistoryBuilder) 

這裏是我的buildMatchHistory方法:

def buildMatchHistory(self, matchHistoryBuilder): 
     # This method takes whatever matches are in match_history.txt, calls MatchHistoryBuilder.buildMatch() on each, 
     # and builds the GUI objects for the match history into the matchHistoryScrollArea. 
     # Globals: self.mainWindow 

     # Open match_history.txt and read json data into matchHistoryData 
     fileLocation = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) 
     fileLocation = fileLocation + '\match_history.txt' 
     with open(fileLocation, 'r') as f: 
      matchHistoryData = json.load(f) 
     matchHistoryData = matchHistoryData["matches"] 

     # Scroll Area Properties 
     matchHistory = self.ui.matchHistoryScrollArea 
     matchHistory.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 
     matchHistory.setWidgetResizable(True) 

     # Container Widget  
     widget = QWidget() 
     # Layout of Container Widget 
     layout = QVBoxLayout(self) 
     for matchIndex, matchInstance in enumerate(matchHistoryData): 
      matchId = matchInstance["matchId"] 
      match = matchHistoryBuilder.buildMatch(summonerId, matchIndex, matchId) 
      layout.addWidget(match) 
     widget.setLayout(layout) 

     matchHistory.setWidget(widget) 

MatchHistoryBuilder.buildMatch()正確返回一個QGroupBox。

如何讓這個方法正確地構建每個匹配對象,將它們添加到QVBoxLayout中,並將該QVBoxLayout添加到我的QScrollArea中?

回答

1

在創建QVBoxLayout,不給它self(在主窗口)作爲父

layout = QVBoxLayout() 

傳遞一個父一個QLayout會自動使該插件的頂層佈局。