使用Lambda表达式连接pyqt中的插槽 [英] Using lambda expression to connect slots in pyqt

查看:432
本文介绍了使用Lambda表达式连接pyqt中的插槽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用lambda函数连接插槽,但是它没有按我期望的方式工作.在下面的代码中,我成功地正确连接了前两个按钮.对于第二个循环连接的第二个问题,这是错误的.我之前的一个人也有同样的问题( Qt-使用lambda连接带有参数的插槽),但此解决方案对我不起作用.我一直盯着屏幕看了半个小时,但我不知道自己的代码有何不同.

I am trying to connect slots with lambda functions, but it's not working the way I expect. In the code below, I succeed in connecting the first two buttons correctly. For the second two, which I connect in a loop, this goes wrong. Someone before me had the same question (Qt - Connect slot with argument using lambda), but this solution doesn't work for me. I've been staring at my screen for a half hour, but I can't figure out how my code is different.

class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(QtGui.QWidget, self).__init__()

        main_layout = QtGui.QVBoxLayout(self)

        # Works:
        self.button_1 = QtGui.QPushButton('Button 1 manual', self)
        self.button_2 = QtGui.QPushButton('Button 2 manual', self)
        main_layout.addWidget(self.button_1)
        main_layout.addWidget(self.button_2)

        self.button_1.clicked.connect(lambda x:self.button_pushed(1))
        self.button_2.clicked.connect(lambda x:self.button_pushed(2))

        # Doesn't work:
        self.buttons = []
        for idx in [3, 4]:
            button = QtGui.QPushButton('Button {} auto'.format(idx), self)
            button.clicked.connect(lambda x=idx: self.button_pushed(x))
            self.buttons.append(button)
            main_layout.addWidget(button)


    def button_pushed(self, num):
        print 'Pushed button {}'.format(num)

按下前两个按钮会产生按下按钮1"和按下按钮2",另外两个都产生按下按钮False",尽管我希望是3和4.

Pressing the first two buttons yields 'Pushed button 1' and 'Pushed button 2', the other two both yield 'Pushed button False', although I expected 3 and 4.

我也不完全了解lambda机制.究竟连接了什么?指向由lambda(替换为参数)生成的函数的指针,还是在信号触发时对lambda函数进行评估?

I also haven't understood the lambda mechanism completely. What exactly gets connected? A pointer to a function that is generated by lambda (with the parameter substituted in) or is the lambda function evaluated whenever the signal fires?

推荐答案

QPushButton.clicked信号发出一个表明按钮状态的自变量.当您连接到lambda插槽时,分配给idx的可选参数将被按钮的状态覆盖.

The QPushButton.clicked signal emits an argument that indicates the state of the button. When you connect to your lambda slot, the optional argument you assign idx to is being overwritten by the state of the button.

相反,将您的连接设置为

Instead, make your connection as

button.clicked.connect(lambda state, x=idx: self.button_pushed(x))

这样,按钮状态将被忽略,并将正确的值传递给您的方法.

This way the button state is ignored and the correct value is passed to your method.

这篇关于使用Lambda表达式连接pyqt中的插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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