Search code examples
pythonpython-3.xpyqtpyqt4exit

What is the necessity of sys.exit(app.exec_()) in PyQt?


I have this code, that works just fine:

import sys
from PyQt4 import QtGui

def main_window():
    app = QtGui.QApplication(sys.argv)
    screen = QtGui.QDesktopWidget().screenGeometry()

    widget = QtGui.QWidget()
    widget.setWindowTitle("Center!")
    widget.setGeometry(200, 100, screen.width() - 400, screen.height() - 200)

    label = QtGui.QLabel(widget)
    label.setText("Center!")
    label.move(widget.frameGeometry().width() / 2, widget.frameGeometry().height() / 2)

    widget.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main_window()

Now in the line where I say sys.exit(app.exec_()), I can also say app.exec_() and both works the same.

So what's the difference and why is it necessary to write sys.exit()?

Thanks in advance.


Solution

  • The exec() call starts the event-loop and will block until the application quits. If an exit code has been set, exec() will return it after the event-loop terminates. It is good practice to pass on this exit code to sys.exit() - but it is not strictly necessary. Without the explicit call to sys.exit(), the script will automatically exit with a code of 0 after the last line of code has been executed. A non-zero exit code is usually used to inform the calling process that an error occurred.