Last active
May 19, 2024 23:29
-
-
Save MaurizioB/abb8f885dcc4562e2bd5ec12c6eacf36 to your computer and use it in GitHub Desktop.
Example of closure issues when using instances without persistent references
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PyQt5.QtWidgets import * | |
class Dummy: | |
def __init__(self): | |
self.box = QGroupBox() | |
self.label1 = QLabel() | |
self.label2 = QLabel() | |
layout = QVBoxLayout(self.box) | |
layout.addWidget(self.label1) | |
layout.addWidget(self.label2) | |
def setText(self, text): | |
self.label2.setText(text) | |
class Test(QWidget): | |
def __init__(self): | |
super().__init__() | |
layout = QVBoxLayout(self) | |
lineEdit = QLineEdit() | |
layout.addWidget(lineEdit) | |
dummy = Dummy() | |
layout.addWidget(dummy.box) | |
# NOTE: keep these commented for now, see below | |
# dummy = BetterDummy() | |
# layout.addWidget(dummy) | |
# comment/uncomment either one of the following: | |
# 1. this creates a closure, so "dummy" isn't deleted | |
lineEdit.textChanged.connect(lambda t: dummy.label1.setText(t)) | |
# 2. this does *not* create a closure, as the only reference that is | |
# actually used is the "setText" function | |
# lineEdit.textChanged.connect(dummy.label1.setText) | |
# point 2 is similar to the following: | |
# setTextFunction = dummy.label1.setText | |
# lineEdit.textChanged.connect(setTextFunction) | |
# this will only work in case 1 | |
lineEdit.textChanged.connect(dummy.setText) | |
# unless you change the two lines on top with those of the NOTE | |
class BetterDummy(QGroupBox): | |
def __init__(self): | |
super().__init__() | |
self.label1 = QLabel() | |
self.label2 = QLabel() | |
layout = QVBoxLayout(self) | |
layout.addWidget(self.label1) | |
layout.addWidget(self.label2) | |
def setText(self, text): | |
self.label2.setText(text) | |
app = QApplication([]) | |
test = Test() | |
test.show() | |
app.exec() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment