python - decorator on slot (PyQt)
问题描述
I use QT to build my GUI, and decorator to record the log. When I use the decorator on a slot, the GUI will crush.
The code is:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def LogInfos(func):
def wrapper(*s, **gs):
print('log')
ret = func(*s, **gs)
return ret
return wrapper
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
layout = QHBoxLayout(self)
btn = QPushButton('test')
layout.addWidget(btn)
btn.clicked.connect(self.testSlot)
@LogInfos
def testSlot(self):
print('test slot')
@LogInfos
def testLog():
print('test log')
if __name__ == '__main__':
testLog()
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
I has tested that the decorator function is OK, and the GUI is ok after remove the decorator.
解决方案
See @ekhumoro's explanation of why, but using the decorated method in the slot is causing your problem due to an incorrect signature.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def LogInfos(func):
def wrapper(*s, **gs):
print('log')
ret = func(*s, **gs)
return ret
return wrapper
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
layout = QHBoxLayout(self)
btn = QPushButton('test')
layout.addWidget(btn)
btn.clicked.connect(self.testSlot)
@LogInfos
def testSlot(self, checked=False):
print('test slot')
@LogInfos
def testLog():
print('test log')
if __name__ == '__main__':
testLog()
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
推荐阅读
- typescript - 用 Observablehq 学习 D3 Js
- javascript - 单击时将表格行重定向到链接
- java - Java 等效于 Go libtrust 公钥 KeyId()
- ruby-on-rails - 有没有办法缩短条件或红宝石中的变量值文本?
- javascript - 尝试删除数组中具有相同值且彼此相邻的重复元素(它们必须保留原始顺序)
- azure-devops - 无法在发布管道定义 api 请求中获取项目详细信息
- visual-studio - 如何在 SSRS 报告中使用多个 iif?
- c# - 两个对象是否需要两个锁?
- arm - Beaglebone Black 不会显示为 /dev/ttyUSB
- javascript - 如何制作一个按钮,当您单击它时会下载一个 excel 文件(phpspreadsheet)