我正在尝试将游戏从PyQt4转换为PyQt5,并且我在转换为较新的信号类型时遇到了一些困难。所以我已经回到了原版,我试图首先使用PyQt4转换信号。注释行是旧的(工作)版本,在它下面是新版本。然而,新的'版本总是将相同的值传递给事件处理程序:0。我尝试过许多微妙的不同版本,似乎没什么用。想法?
self.cellButtonNames = [self.ui.cell0Button, self.ui.cell1Button, self.ui.cell2Button, self.ui.cell3Button, self.ui.cell4Button, self.ui.cell5Button,
self.ui.cell6Button, self.ui.cell7Button, self.ui.cell8Button, self.ui.cell9Button, self.ui.cell10Button, self.ui.cell11Button,
self.ui.cell12Button, self.ui.cell13Button, self.ui.cell14Button, self.ui.cell15Button, self.ui.cell16Button, self.ui.cell17Button,
...,
self.ui.cell126Button, self.ui.cell127Button, self.ui.cell128Button, self.ui.cell129Button, self.ui.cell130Button, self.ui.cell131Button,
self.ui.cell132Button, self.ui.cell133Button, self.ui.cell134Button, self.ui.cell135Button, self.ui.cell136Button, self.ui.cell137Button,
self.ui.cell138Button, self.ui.cell139Button, self.ui.cell140Button, self.ui.cell141Button, self.ui.cell142Button, self.ui.cell143Button]
# This will connect all of the ball buttons to one slot (Event Handler) and pass the cell number to that event handler when signalled.
# This elimates the need for 144 event handling methods! :-)
cellNumber = 0
for buttonName in self.cellButtonNames:
# self.connect(buttonName, QtCore.SIGNAL("clicked()"), lambda who=cellNumber: self.ballClicked(who))
buttonName.clicked.connect(lambda who=cellNumber: self.ballClicked(who))
cellNumber += 1
@QtCore.pyqtSignature("") # otherefore only want ne signal for this autoconnect.
def ballClicked ( self, cellNumber):
print("Ball %i clicked" % cellNumber)
答案 0 :(得分:2)
这是一个非常着名的"陷阱"。
有一些信号(如clicked
和triggered
)具有始终发送值的默认参数。对于按钮和操作,这是表示其当前已检查状态的bool
(即使它们可能未设置为可检查状态)。
要解决此问题,您可以像这样连接信号:
buttonName.clicked.connect(
lambda checked, who=cellNumber: self.ballClicked(who))
但是,在这种特殊情况下,您可能还需要考虑使用QButtonGroup。这只需要一个信号连接,并且,作为一个附带好处,您还可以获得用于管理按钮的现成界面。