PyQT 将 lambda 函数连接到 Signal [英] PyQT Connecting lambda function to Signal

查看:28
本文介绍了PyQT 将 lambda 函数连接到 Signal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题.我正在尝试将 lambda 函数连接到 Signal 以最终传递一些额外数据.

I'm stuck with the following problem. I'm trying to connect a lambda function to a Signal for passing some extra data eventually.

def createTimeComboBox(self,slotCopy):
    timeComboBox = QComboBox()

    #...

    cmd = lambda func=self.test:func()
    self.connect(timeComboBox, SIGNAL("currentIndexChanged(int)"),cmd)

#...

def test(self, value):
    print value

当我运行 createTimeComboBox(), 时,我收到此错误:

When I run createTimeComboBox(), I get this error:

TypeError: 'int' object is not callable

变化

self.connect(timeComboBox, SIGNAL("currentIndexChanged(int)"),cmd)

self.connect(timeComboBox, SIGNAL("currentIndexChanged(int)"),self.test)

工作正常,但我也希望能够传递 slotCopy 变量,因此假设我需要使用 lambda 方法.

works fine, but I would like to be able to pass the slotCopy variable as well, so assumed that I need to use the lambda approach.

我之前使用 QPushButtonclicked() 信号完成了此操作,效果很好.

I had done this previously with a QPushButton's clicked() signal and that worked fine.

def createToDoctorButton(self,extraData):
    toDoctorButton = QPushButton()

    cmd = lambda func=self.goToDoctor:func(extraData)
    self.connect(toDoctorButton,  SIGNAL('clicked()'),cmd)

    return toDoctorButton

def goToDoctor(self,extraData):
    print extraData

我希望这是有道理的 - 有没有人有任何想法?感谢您的任何建议!干杯戴夫

I hope this makes sense - does anyone have any ideas? Thanks for any suggestions! Cheers Dave

推荐答案

你的 lambda 接受一个参数 (func):

Your lambda accepts a parameter (func):

lambda func=self.test:func() 

虽然参数有默认值,但是如果传入参数就会被替换掉.查看信号 currentIndexChanged(int),表明该信号将传递一个整数参数.func 将是来自 currentIndexChanged 的整数.稍后,执行 func() 将有效地尝试调用一个显然不合法的整数对象(如错误所示)

Although the parameter has a default, it will be replaced if a parameter is passed. Looking at the signal, currentIndexChanged(int), shows that the signal will pass an integer parameter. func will be the integer coming from currentIndexChanged. Later, doing func() will be effectively trying to call an integer object which obviously is not legal (as the error indicates)

您需要在 lambda 中使用另一个参数来捕获"传递的参数而不覆盖 func 参数:

You need another parameter in your lambda to "catch" the passed parameter without overriding the func parameter:

cmd = lambda value, func=self.test: func(value)

顺便说一下,你的 test 方法需要一个参数,所以你不能只做 func().

By the way, your test method expects a parameter, so you can't just do func().

clicked() 信号没有这个问题,因为它没有传递参数来替换默认值.

You didn't have that problem with the clicked() signal because it doesn't pass a parameter to replace the default value.

这篇关于PyQT 将 lambda 函数连接到 Signal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆