How Can I Use A Decorator On A Pyqt Signal?
I have a decorator that is supposed to try / except any method given to the wrapper so that it can log on the GUI any errors encountered in order to give the user a chance to under
Solution 1:
The issue doesn't seem to be with your decorator, but rather with connecting a method to the valueChanged
signal. Since this signal emits data (the new value being set), you need to add an additional argument to the __pressed
method that represent this data.
This is a simplified version of your code - you can see that the exception is properly handled by the decorator when the value in the spinbox gets too high.
import sys
from PyQt5.QtWidgets import QSpinBox, QWidget, QHBoxLayout, QApplication
defmy_decorator(method_reference):
defwrapper(*args, **kwargs):
try:
return method_reference(*args, **kwargs)
except Exception as e:
print("saved from " + str(e))
return wrapper
classFoo(QWidget):
def__init__(self):
super(Foo, self).__init__()
layout = QHBoxLayout()
self.setLayout(layout)
self.spinbox = QSpinBox()
self.spinbox.valueChanged.connect(self.pressed)
layout.addWidget(self.spinbox)
@my_decoratordefpressed(self, new_value):
print(f"spin box now has a value of {new_value}")
if new_value > 5:
raise ValueError(f"Value {new_value} is too high!")
if __name__ == '__main__':
app = QApplication(sys.argv)
foo = Foo()
foo.show()
sys.exit(app.exec_())
Now, in my experience with PyQt, you don't always need to add the extra argument representing the data being sent by the signal. But in this case I'm assuming it is (somehow) mandatory due to the wrapping of the slot method. People more experienced with the library are free to correct me :-)
Post a Comment for "How Can I Use A Decorator On A Pyqt Signal?"