Last Updated: February 25, 2016
·
588
· tonnydourado

Decorators and Qt actions

So, when using the standard PyQt bindings from Riverbank (I've never used PySide), I find myself using this hack a lot, to solve a implementation "problem" on PyQt, where signals ended up being connected to two slots, causing the method to be called twice:

def on_actionSomeAction_triggered(self, checked=None):
    if checked is None:
        return

Although it's pretty simple code, it can be both boring and ugly when you have lots of methods. So, I implemented a simple decorator to avoid the code duplication:

def if_none_return(function):
    def decorated_function(self, checked=None):
        if checked is None:
            return
        function(self, checked)
    decorated_function.func_name = function.func_name
    return decorated_function

You can use it like this:

@if_none_return
def on_actionSomeAction_triggered(self, checked=None):
    if checked is None:
    return

The python magic even take care of all the method bounding stuff, just stick to the conventions.

PS: Anyone know how I set syntax highlighting on this thing? Or is it automagically set? UPDATE: Never mind, it's automatic.