PyQT5 绑定函数的传参(connect 带参数)

使用PyQt编程过时,经常会遇到给槽函数传递自定义参数的情况。

 

采用 lamda:

示例1

self.but1.clicked.connect(lambda: self.mySlot(1))
self.but2.clicked.connect(lambda: self.mySlot(2))
def mySlot(self, param):
    if param == 1:
        ...
    elif param == 2:
        ...

 

示例2

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

# 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"

 

 

 

REF

https://www.jianshu.com/p/588a7384bbb3

https://zhuanlan.zhihu.com/p/371042469

 

posted @ 2022-01-16 18:09  emanlee  阅读(13495)  评论(0编辑  收藏  举报