In PyQt5 how do you assign an event function with your own variable to a QWidget in loop?


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)

        label2 = QLabel("label2")
        label2.mouseReleaseEvent = lambda event: self.changeText(event, label2)

        for i in range(0,2):
            label = QLabel("label")
            label.mouseReleaseEvent = lambda event: self.changeText(event, label)

    def changeText(self, event, label):

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?

Asked By: Mikhail Valiev



This is happening because python binds the value of label latter until it’s called.

You can get around this by writing the handler like so.

label.mouseReleaseEvent = lambda event, label=label: self.changeText(event, label)


Answered By: Oluwafemi Sule
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.