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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With