(五 交互-1)PyQT5 绑定函数的传参

理解说明

如下内容很好,建议阅读。
A PyQt button event can be connected in the normal way to a function so that the function receives the default signal arguments (in this case the button checked state):

def connections(self):
    my_button.clicked.connect(self.on_button)

def on_button(self, checked):
    print checked   # prints "True"

Or, the default signal arguments can be overridden using lambda:

def connections(self):
    my_button.clicked.connect(lambda: self.on_button('hi'))

def on_button(self, message):
    print message   # prints "hi"

Is there a nice way to keep both signal arguments so it can be directly received by a function like below?
YES!

Your lambda could take an argument:

def connections(self):
    my_button.clicked.connect(lambda checked: self.on_button(checked, 'hi'))

def on_button(self, checked, message):
    print checked, message   # prints "True, hi"

Or you could use functools.partial:

# imports the functools module
import functools 

def connections(self):
    my_button.clicked.connect(functools.partial(self.on_button, 'hi'))

def on_button(self, message, checked):
    print checked, message   # prints "True, hi"

来源:Pass extra arguments to PyQt slot without losing default signal arguments

示例

def fn_init_event(self):
    template_num = len(self.list_comparison_result)
    for i in range(template_num):
        dict_template = self.list_comparison_result[i]
        self.list_button[i].clicked.connect(lambda ignore, dict_template=dict_template: self.fn_get_detail(dict_template, self.test_type, self.product_tag)) # The boolean value gets assigned to ignore (and is ignored) and x (i.e., this) is properly used as the argument of the function

其中 (lambda ignore, dict_template=dict_template: self.fn_get_detail(dict_template, self.test_type, self.product_tag) 中的 dict_template=dict_template 是为了指定当前的 dict_template 为当前传入的值,而非循环中的最后一个 dict_template。这是另外一个很 tricky 的地方了。

你可能感兴趣的:((五 交互-1)PyQT5 绑定函数的传参)