Important: Please read the Qt Code of Conduct -

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!

  • @Kryzar
    You want to not decorate the PySide2 slot with @Slot()? Why does that make a difference to you? Yes, you absolutely can use Python lambdas as the slot, in both PySide2 & PyQt5, if that is your question.

  • @JonB
    Thanks for your answer. This is my problem, I have a slot my_slot defined like this:

    def my_slot(self, s: str, b: bool):

    and this slot is connected to two signals (signal1 and signal2) which both emit the string s. However, I want different values for the boolean b, 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.

  • @JonB
    Exactly the same, it's horrible. Anyway, thanks a lot!

  • Lifetime Qt Champion

    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

  • @SGaist
    Thanks a lot. It would be nice to have a clear and definitive answer from Qt directly, I may try to contact them but I am not sure how to do that.

    Edit: grammar.

Log in to reply