将额外的参数传递给 PyQt 插槽而不丢失默认信号参数 [英] Pass extra arguments to PyQt slot without losing default signal arguments
本文介绍了将额外的参数传递给 PyQt 插槽而不丢失默认信号参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
PyQt 按钮事件可以以正常方式连接到函数,以便函数接收默认信号参数(在本例中为按钮选中状态):
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"
或者,可以使用 lambda
覆盖默认信号参数:
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?
def on_button(self, checked, message):
print checked, message # prints "True, hi"
推荐答案
你的 lambda
可以接受一个参数:
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"
或者你可以使用 functools.partial
:
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"
这篇关于将额外的参数传递给 PyQt 插槽而不丢失默认信号参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文