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):

    def initUI(self):
        btn = QPushButton('Quit', self)
        btn.move(50, 50)

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

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

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

close window pyqt


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.


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.


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