Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 494
Amir Shabani Avatar asked Aug 04 '17 13:08

Amir Shabani


People also ask

What is the purpose of app QApplication SYS argv?

Passing sys. argv to QApplication at startup allows you to customize the behavior of Qt from the command-line. If you don't want to pass command-line arguments to Qt you can skip passing sys.


1 Answers

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.

like image 87
ekhumoro Avatar answered Sep 28 '22 22:09

ekhumoro