Skip to content

Instantly share code, notes, and snippets.

@MaurizioB
Last active May 19, 2024 23:29
Show Gist options
  • Save MaurizioB/abb8f885dcc4562e2bd5ec12c6eacf36 to your computer and use it in GitHub Desktop.
Save MaurizioB/abb8f885dcc4562e2bd5ec12c6eacf36 to your computer and use it in GitHub Desktop.
Example of closure issues when using instances without persistent references
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