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

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

问题描述

我正在尝试使用 lambda 函数连接插槽,但它没有按我预期的方式工作.在下面的代码中,我成功地正确连接了前两个按钮.对于我循环连接的后两个,这是错误的.在我之前有人有同样的问题(Qt - Connect slot with argument using 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天全站免登陆