Lambda or partial as slot
-
Hi!
Is it possible to connect a python lambda or functools.partial as a PySide2 Slot? It is possible with the C++ version of Qt but it seems that it is recommended to always use slots that have been decorated in PySide2, as stated in the note here.
I would do that in order to pass different arguments to my slots depending on which signal was emitted (my slot is connected to different signals). If you know a better way to do that I am greatly interested but I would like an answer to the original question nonetheless.
Thanks a lot!
-
@JonB
Thanks for your answer. This is my problem, I have a slotmy_slot
defined like this:@Slot(str) @Slot(bool) def my_slot(self, s: str, b: bool): …
and this slot is connected to two signals (
signal1
andsignal2
) which both emit the strings
. However, I want different values for the booleanb
, depending on which signal was emitted. I thought I would do something like this.self.signal1.connect(functools.partial(self.my_slot, b=True)) self.signal2.connect(functools.partial(self.my_slot, b=False))
This way, I do not have to define to decorated slots (one for each signal). The problem is that
functools.partial(self.my_slot, …))
is not decorated and I wanted to know if this could cause problems. From the documentation I did not understand if the decorator is required or not. Let me know if this is not clear of if I can be more precise.Edit: typo.
-
@Kryzar said in Lambda or partial as slot:
From the documentation I did not understand if the decorator is required or not.
Nor do I! Google for
pyside2 @slot
, you get some old answers for PySide/PyQt. I can only say that you don't seem to have to use it (e.g. look at lambda), One stackoverflow talks about:If you don't use the slot decorator, the signal connection mechanism has to manually work out all the type conversions to map from the underlying C++ function signatures to the Python functions. When the slot decorators are used, the type mapping can be explicit.
Your guess/understand is as good/better than mine, so I'll leave it at that now.
-
AFAIR, the decorator is not mandatory but it provides an optimisation performance.
It also has the advantage of making things explicit in terms of code comprehensionY