Why do I need a variable to point to my QWidget?

Why does the example below only work when creating a useless variable _ ?

The variable _ is assigned and never used. I would suggest that a good compiler would optimize and not even create it, but that really matters.

If I remove _ = and leave only Test() , then a window is created, but it instantly flickers and disappears, and python is eternally maintained.

Here is the code:

 import sys from PyQt4 import QtGui class Test(QtGui.QWidget): def __init__(self): super().__init__() self.show() app = QtGui.QApplication(sys.argv) _ = Test() sys.exit(app.exec_()) 
+5
source share
2 answers

This is a very good question, and in the past I ran into a lot of strange problems due to this fact with my PyQt widgets and plugins, this is mainly due to the python collector garbage .

When you assign your instance of this dummy variable _ before entering the main Qt loop, there will be a live link that the garbage collector will not collect, so the widget will not be destroyed.

+3
source

@BPL is true, but I wanted to add that you do not need to assign it _. You can assign it to any variable. You just need a variable that refers to the object you created, otherwise it will be collected by the garbage collector after creation.

0
source

All Articles