PyQt Close window

The simplest way to close a window is to click the right (Windows) or left (macOS) 'X' button on the title bar. Now let's see how to close the window through programming. We'll also take a quick talk about signals and slots.

Related course: Create Desktop Apps with Python PyQt5

Close the window.

The program below creates a button. If you click the button, it will close the program. It closes the program programatically.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import QCoreApplication

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        btn = QPushButton('Quit', self)
        btn.move(50, 50)
        btn.resize(btn.sizeHint())
        btn.clicked.connect(QCoreApplication.instance().quit)

        self.setWindowTitle('Quit Button')
        self.setGeometry(300, 300, 300, 200)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

You have created a 'Quit' button. Now click this button to exit the application.

close window pyqt

Description

from PyQt5.QtCore import QCoreApplication

Load the QCoreApplication class for the QtCore module.

btn = QPushButton('Quit', self)

Create one pushbutton.

This button (btn) is an instance of the QPushButton class.

For the first parameter of the constructor QPushButton(), is the text that will appear on the button, and the second parameter enters the parent widget where the button will be located.

btn.clicked.connect(QCoreApplication.instance().quit)

Event processing in PyQt5 is done with the signals and slot mechanism. Clicking the button (btn) will create a 'clicked' signal. The instance() method returns the current instance.

The 'clicked' signal is connected to the quit() method that exits the application.

QCoreApplication.instance().quit

This allows communication between the sender and receiver, both objects. In this example, the sender is a QPushbutton (btn) and the receiver is an application object (app).

Related course: Create Desktop Apps with Python PyQt5