Ahsanul Haque Ahsanul Haque - 13 days ago 6
Python Question

Why do I need the Widget instance assigned to a variable in PyQt5?

All I am doing here is creating a custom widget inheriting the default behaviour of

QWidget
.

from PyQt5.QtWidgets import QApplication, QWidget
import sys
from PyQt5.QtGui import QIcon

class CustomWidget(QWidget):
def __init__(self):
super().__init__()
self.setUI()

def setUI(self):
self.setGeometry(300,300,0,0)
self.setWindowTitle('CustomWidget')
self.setWindowIcon(QIcon('icon.png'))

self.show()


Then comes the part of creating instance. When I initialize and run with following snippet, the widget isn't visible to me.

if __name__ == "__main__":
app = QApplication(sys.argv)
CustomWidget() <----------------------This line creates the problem
sys.exit(app.exec_())


However,

somevalue = CustomWidget()


And,

_ = CustomWidget()


My question is, why PyQt is showing this behavior? Why I have to assign the instance to some variable even if I don't use it later?

Answer

The reason is python's reference counting.

As soon as an object has no no more references to it (assigning it to a variable counts as a reference), it gets deleted by the interpreter.