user14094230
user14094230

Reputation:

Close method does not close window pyqt5

A basic example, where I'm trying to call the close() method to close the main window, doesn't close the window, I have to close it manually.

from PyQt5 import QtWidgets
import sys
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Should close")
        self.close()  
        
app=QtWidgets.QApplication(sys.argv)
w=MainWindow()
w.show()
app.exec_()

If I put self.show() in the init method, instead of using w.show(), the window will open and close, but then the program doesn't stop running. How does one close the window and the application automatically?

Upvotes: 0

Views: 1272

Answers (1)

eyllanesc
eyllanesc

Reputation: 243945

If you analyze your logic you will see that what you indicate is expected, when you create the widget it is closing it since you called the close() method but in the next line you invoke the show() method that will make the window visible.

To understand it better I can tell you that your code is equivalent to:

from PyQt5 import QtWidgets
import sys

app = QtWidgets.QApplication (sys.argv)
w = QtWidgets.QMainWindow ()
w.setWindowTitle ("Should close")
w.close ()
w.show ()
app.exec_ ()

As you have noticed that a window closes does not imply that the application ends since they are 2 orthogonal concepts. If you want the close() method to also terminate the program then you must invoke the close() method when the eventloop starts:

from PyQt5 import QtCore, QtWidgets
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Should close")
        QtCore.QTimer.singleShot(0, self.close)


app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()

Why is it necessary for the eventloop to terminate the application when closing the only open window? Well, because the evenloop (QApplication in this case) uses the flag quitOnLastWindowClosed, which by default is true, which makes the application terminate when the last window is closed.

Upvotes: 1

Related Questions