我编写了一个使用PyQt构建GUI的程序。在Qt设计器中,我有一个主窗口,其中有一个QTabWidget,QTabWidget中有一个QScrollArea。我尝试用匹配数据动态构建一个匹配列表,将每个匹配添加到小部件的布局中,并将此布局放入QScrollArea中。目前,我的代码可以很好地完成此任务,但它会引发以下错误:
QLayout: Attempting to add QLayout "" to MainWindow "MainWindow", which already has a layout
这对我来说是有道理的,但我不知道如何解决它。我甚至不知道我拥有的东西是如何发挥作用的,这使得它更难修复。在
在我的MainWindow__init__()
方法中,我创建了MatchHistoryBuilder类的一个实例(它构建了每个匹配),调用了一个buildMatchHistory()方法(位于MainWindow类中),然后将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?在
创建
QVBoxLayout
时,不要将其self
(主窗口)作为父窗口将父级传递给
QLayout
将自动使其成为该小部件的顶层布局。在相关问题 更多 >
编程相关推荐