Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt QWidget window closes immediately upon showing?

I realize that this question has been asking several times before, though none of them seem to apply to my situation. I have installed PyQt, and am simply trying to open up a window as such:

import sys
from PyQt4 import QtGui as qt

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

All the other questions I have looked at on here usually were caused by an error with the window going out of scope because of the window's show method being called from within a function, or something similar.

My code uses no functions at all so this cannot be the issue. This should work as it is, no? I am following this tutorial:

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

and at time 8:58, the instructor has pretty much exactly what I have written, and their window shows up and stays around just fine. Mine displays for a fraction of a second and then closes.

Screen shot of the code block from the video to compare to the code block provided here:

Demo code that works

like image 511
pretzlstyle Avatar asked Aug 04 '15 17:08

pretzlstyle


1 Answers

Without seeing all of your code, I'm assuming that you're missing the sys.exit() bit.

For your specific code sys.exit(segmentation.exec_()) would be what you needed.

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

A little bit of detail of what's going on here.

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

main = qt.QWidget() and main.show() creates the Widget and then displays.

When executing the python script, this does exactly what you tell it to:

  1. Create an application
  2. Create a widget
  3. Show the widget
  4. Finished. End of the script.

What the sys.exit() does is cleanly closes the python script. segmentation.exec_() starts the event driven background processing of QT. Once the segementation.exec_() is finished (user closes the application, your software closes the application, or a bug is encountered) it'll return a value which is then passed into the sys.exit() function which in turn terminates the python process.

like image 168
James Mertz Avatar answered Oct 18 '22 05:10

James Mertz