Please nominate your Qt Champions for 2021!

different behavior of pressed vs clicked with lambdas

  • I'm using lambda functions to define the actions for dynamically generated buttons. To "freeze" the value of the loop variable "i" assign it to a local variable "n" in the way described here

    This works fine for 'pressed',

    button.pressed.connect(lambda a=i : print(f'pressed {a}'))

    --> "pressed 7"

    but somehow fails for 'clicked'.

    button.clicked.connect(lambda a=i: print(f'clicked {a}'))

    --> "clicked False"


    from PySide2.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
    app = QApplication()
    window = QWidget()
    layout = QVBoxLayout()
    for i in range(10):
        button = QPushButton()
        if i > 4:
            button.setText(f'pressed {i}')
            button.pressed.connect(lambda a=i : print(f'pressed {a}'))
            button.setText(f'clicked {i}')
            button.clicked.connect(lambda a=i: print(f'clicked {a}'))

    I fail to understand why this happens. Is there a fundamental difference in the way that 'pressed' and 'clicked' are handled? Or is this a bug?

  • @VirtualFloat Change to:

    • button.clicked[bool].connect(lambda checked, a=i: print(f'clicked {a}'))


    • button.clicked.connect(lambda *args, a=i: print(f'clicked {a}'))

    See for more information.

  • Ah, so clicked gets an argument where pressed doesn't. Thanks!

    I like the button.clicked.connect(lambda *args, a=i: print(f'clicked {a}')) solution because it will work even if the signature would change.

Log in to reply