【发布时间】:2026-02-20 05:10:01
【问题描述】:
当使用 UI 元素的 pyqt 信号(例如带有修饰方法的按钮)时,信号似乎不起作用。请在下面找到最小可重现代码。
import sys
from PyQt5.QtWidgets import (QWidget, QToolTip, QPushButton, QApplication)
from PyQt5.QtGui import QFont
def ui_decorator(target_func):
def call(self, *args, **kwargs):
print("Init.")
ret_code = target_func(self, *args, **kwargs)
print("Deinit.")
return ret_code
return call
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
QToolTip.setFont(QFont('SansSerif', 10))
self.setToolTip('This is a <b>QWidget</b> widget')
btn = QPushButton('Button', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')
btn.clicked.connect(self.button_action)
btn.resize(btn.sizeHint())
btn.move(50, 50)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Tooltips')
self.show()
@ui_decorator
def button_action(self):
print("Button Clicked")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
在上面的代码中,如果单击按钮,则对 button_action 函数的调用将失败,并显示以下消息:TypeError: button_action() takes 1 positional argument but 2 were given。但是当我不使用装饰器 (ui_decorator) 时,代码可以正常工作,即使它仍然只需要 1 个位置参数。
谢谢
【问题讨论】: