我编写了一个使用PyQt构建GUI的程序。从Qt Designer,我有一个MainWindow,一个QTabWidget,以及QTabWidget内的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?
答案 0 :(得分:2)
创建QVBoxLayout
时,请不要将self
(MainWindow)作为父
layout = QVBoxLayout()
将父级传递给QLayout
会自动将其作为该小部件的顶级布局。