Connecting Slots and Signals Dynamically in PyQt4
In PyQt4, connecting multiple slots to signals programmatically can lead to unexpected behavior when done within a loop.
Issue:
Consider creating a calculator with dynamically generated number buttons within a loop. If the 'clicked()' signal of each button is connected as follows:
def __init__(self): for i in range(0, 10): self._numberButtons += [QPushButton(str(i), self)] self.connect(self._numberButtons[i], SIGNAL('clicked()'), lambda : self._number(i))
Problem:
When any button is clicked, they all print '9'. This behavior arises from Python's scoping and closure semantics. The lambda expression references the variable i, which within the loop, evaluates to the final value, '9'.
Solution:
To avoid this issue, pass i as a keyword argument with a default value:
self._numberButtons[i].clicked.connect(lambda checked, i=i: self._number(i))
Alternatively, use functools.partial for a cleaner approach:
self._numberButtons[i].clicked.connect(partial(self._number, i))
These solutions isolate i within the lambda expression, ensuring that each button triggers its intended action when clicked.
The above is the detailed content of How to Connect Slots and Signals Dynamically in PyQt4 Without Unexpected Behavior?. For more information, please follow other related articles on the PHP Chinese website!