Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to keep a variable pointing to my QWidget?

Tags:

python

pyqt4

Why does the example below only work if the useless _ variable is created?

The _ variable is assigned and never used. I would assume a good compiler would optimize and not even create it, instead it does make a difference.

If I remove _ = and leave just Test(), then the window is created, but it flickers and disappears immediately, and python hangs forever.

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_())
like image 798
stenci Avatar asked Oct 19 '22 03:10

stenci


1 Answers

That's a very good question and I've faced a lot of weird problems in the past because of this fact with my PyQt widgets and plugins, basically that happens thanks to the python garbage collector.

When you assign your instance to that _ dummy variable before entering the Qt's main loop, there will be a living reference that will avoid to be collected by the garbage collector, therefore the widget won't be destroyed.

like image 90
BPL Avatar answered Oct 21 '22 05:10

BPL