I'm new to python and PyQt. To illustrate my problem I made this code:
class Window(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
layout = QHBoxLayout(self)
label1 = QLabel("label1")
label1.mouseReleaseEvent = lambda event: self.changeText(event, label1)
layout.addWidget(label1)
label2 = QLabel("label2")
label2.mouseReleaseEvent = lambda event: self.changeText(event, label2)
layout.addWidget(label2)
for i in range(0,2):
label = QLabel("label")
label.mouseReleaseEvent = lambda event: self.changeText(event, label)
layout.addWidget(label)
def changeText(self, event, label):
label.setText("pressed")
So, we have 4 labels, which im trying to make clickable. Label1 and label2 working as intended. You click a label, and text changing. But for those labels which created in loop the assignment works incorrectly. Label which passed to a function is always the last one. No matter which label you click, the last one will change its text. This behavior seems magical to me. I need an advise on how to organize the loop in such a way so every label pass itself into a function?