与 QPushButton 一起使用时,错误 lambda 缺少 1 个必需的位置参数 [英] Error lambda missing 1 required positional argument when using with QPushButton
问题描述
这是我的全部代码:
import sys
from PySide2.QtCore import Qt
from PySide2.QtWidgets import (
QApplication,
QHBoxLayout,
QLabel,
QMainWindow,
QPushButton,
QVBoxLayout,
QWidget,
)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
v = QVBoxLayout()
h = QHBoxLayout()
for a in range(10):
button = QPushButton(str(a))
button.clicked.connect(lambda checked, a=a: self.button_clicked(a)) # error here
h.addWidget(button)
v.addLayout(h)
self.label = QLabel("")
v.addWidget(self.label)
w = QWidget()
w.setLayout(v)
self.setCentralWidget(w)
def button_clicked(self, n):
self.label.setText(str(n))
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
当我运行这段代码时,我得到一个这样的窗口:
When I run this code, I get a window like this:
在按钮下方,有一个 QLabel,我希望当我单击任何按钮时,按钮的标签将引用此 QLabel,但我在终端中遇到了一堆令人困惑的错误.我的代码有什么问题,帮帮我,谢谢.
Below the buttons, there is a QLabel, and I want when I click on any button, the button's label will refer to this QLabel, but I get a bunch of confusing errors in the terminal. What's wrong with my code, help me, thanks.
推荐答案
clicked 信号过载,因此它接受 2 个签名,可以发送或不发送 bool.默认签名取决于库,在这种情况下,PySide2 默认情况下似乎不会发送已检查"的签名.参数,与 PyQt5 不同.
The clicked signal is overload so it accepts 2 signatures where it can send a bool or not. The default signature depends on the library, in this case it seems that PySide2 by default does not send the "checked" parameter, unlike PyQt5 that does.
解决办法是指明签名:
button.clicked[bool].connect(lambda checked, a=a: self.button_clicked(a))
这篇关于与 QPushButton 一起使用时,错误 lambda 缺少 1 个必需的位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!