Pass extra arguments to PyQt slot without losing default signal arguments

孤人 提交于 2021-02-05 20:29:22

问题


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?

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

回答1:


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"


来源:https://stackoverflow.com/questions/38090345/pass-extra-arguments-to-pyqt-slot-without-losing-default-signal-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!