Does the PyQt QWidget window close immediately after display?

I understand that this question has been asked several times before, although none of them seem to be applicable to my situation. I installed PyQt and just try to open the window as such:

import sys from PyQt4 import QtGui as qt segmentation = qt.QApplication(sys.argv) main = qt.QWidget() main.show() 

All other issues that I have considered here were usually caused by an error when a window goes out of scope due to the window show method being called from a function or something like that.

My code does not use any functions at all, so this may not be a problem. It should work as it is, no? I follow this guide:

https://www.youtube.com/watch?v=JBME1ZyHiP8

and at 8:58, the instructor has exactly what I wrote, and their window appears and remains in order. The mine is displayed for a split second and then closes.

Screenshot of the code from the video for comparison with the code block presented here:

Demo code that works

+6
source share
1 answer

Without seeing all of your code, I assume that you are missing the sys.exit() bit.

For your specific code, sys.exit(segmentation.exec_()) will be what you need.

 segmentation = qt.QApplication(sys.argv) main = qt.QWidget() main.show() sys.exit(segmentation.exec_()) 

A bit of detailed information about what is happening here.

segmentation = qt.QApplication(sys.argv) creates the actual application.

main = qt.QWidget() and main.show() creates a widget and then displays.

When executing a python script, this does exactly what you say:

  • Application creation
  • Widget creation
  • Show widget
  • completeness. The end of the script.

What sys.exit() does is the pure closure of the python script. segmentation.exec_() starts the background processing of the QT event. After segementation.exec_() (the user closes the application, your software closes the application or detects an error), it returns a value, which is then passed to the sys.exit() function, which, in turn, terminates the python process.

+11
source

All Articles