Search code examples
pythonpyqtshowqapplication

PyQt5 Widget Disappears When No Breakpoint is Used


Don't critisize me using different classes - the reasons for his is becausethere will be more GUIs in my project created by the QtDesigner, but this should not be important for now.

In general, I have two Python scripts:

main.py:

from PyQt5 import QtCore, QtWidgets, QtGui
import sys
import time

from gui_class import Gui

app = QtWidgets.QApplication(sys.argv)

gui = Gui()

sys.exit(app.exec_())

gui_class.py:

from PyQt5 import QtWidgets

class Gui():
    def __init__(self):
        w = QtWidgets.QWidget()
        w.resize(500, 500)
        self.button = QtWidgets.QPushButton(w)
        self.button.setGeometry(100, 100, 300, 300)
        w.show()

If I run the main.py-script, then the window appears for a split second and disappears right away. I can't see it, I can't click it. The code does not terminate, though. It's still waiting for the application to finish - I can't do anything, though.

If I put a breakpoint before the line saying w.show() in the gui_class.py and simply continue the code after it stopped in that line, then the GUI is visible and I can click the button and the code terminates after I close the window - everything works as expected.

I am using PyQt5: 5.15.2 with Python3.7.


Solution

  • The problem is that w is a local variable that will be destroyed when the scope where it was created finishes executing. The solution is to extend its life cycle by increasing its scope by making it an attribute of the class, for this you must change w with self.w.