13

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.

2
  • 1
    It just makes you immediately close the program after the Qt Event loop is over, which is in most cases when you close the GUI
    – Xatyrian
    Aug 4, 2017 at 13:32
  • QApplication::exec: Must be called from the main thread
    – CS QGB
    Jul 28, 2021 at 3:09

1 Answer 1

20

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.