Reputation: 17718
The commands array contains a list of tuples each one containing a name and the function that will handle the event. For each pair a new button is created and added to a QListWidget. The problem is that all the buttons end up calling the same handler function. The last one in the list. I have checked with my debugger and it does loop correctly through the list and the correct handler function is passed on each loop.
This is the function generating the buttons.
def load_commands(self):
for name, handler in commands:
btn = QtGui.QPushButton(name)
btn.clicked.connect(lambda: handler(self))
item = QtGui.QListWidgetItem()
item.setSizeHint(Qt.QSize(0, 30))
self.list_commads.addItem(item)
self.list_commads.setItemWidget(item, btn)
[EDIT] Just in tried setting btn and item to None at the end of each loop. It did not work.
Upvotes: 0
Views: 27
Reputation: 120678
You need to keep a reference to each handler, otherwise only last one will be left in scope. One way to do that is with a default argument:
btn.clicked.connect(lambda *args, handler=handler: handler(self))
Note that clicked
always sends the checked-state of the button, so *args
is there to avoid clobbering the default argument.
Upvotes: 1