Pyqt5 close all windows

Post Views: 1,442

Hey folks, This tutorial will help you to close a window in PyQt5 in Python. This can be achieved by using a simple method of the QWidget class. We will use that method and learn how to achieve our goal in a few ways. So for this, we are going to use some libraries of Python namely: PyQt5 and sys.

Using:

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys

How to close a window in PyQt5

To close a window in PyQt5 we use the .close() method on that window. We can simply achieve this by calling the .close() method whenever we want to close the window or by some following ways:

  1. Calling the .close() method whenever needed.
  2. Binding to a PushButton to trigger the .close() method.
  3. Creating a QAction and adding it to the window to trigger the .close() method.

Calling the .close() method whenever needed

Create your PyQt5 application and just call the .close() method whenever that window needs closing. For example:

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Close Window")
        self.l1=QLabel("Let's Close this Window")
        self.l1.setAlignment(Qt.AlignCenter)
        self.setCentralWidget(self.l1)
        self.close()    #Closes the window at this point
app=QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()

The above program creates a simple PyQt5 application with a QLabel as its central widget and then finally, closes it. So the window will be created, the widget will be added but it won’t be displayed as it was closed as soon as it was created.

NOTE: The above-mentioned program is just a demonstration on how to use .close() method when needed to close a window. It’s not a full-flexed application. So nothing will be displayed as mentioned earlier.

Binding to a PushButton to trigger the .close() method

In this way of closing the window, we create a QPushButton() and then bind a function(to close the window) to it which is triggered when that button is clicked. For example:

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Close Window")
        self.b1=QPushButton("Let's Close this Window")
        self.b1.clicked.connect(lambda:self.close()) #function binded to the button self.b1
        self.setCentralWidget(self.b1)
app=QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()

The above program creates a simple PyQt5 application with a QPushButton() as its central widget and then binds a function to trigger on click. The function is a simple lambda function that calls the self.close() method.It’s bound to QPushButton() using the .clicked.connect() method.So when the button is clicked the window closes.

Creating a QAction and adding it to the window to trigger the .close() method

How to close a window in PyQt5

In this way of closing the window, we create a QAction() and then add that action to the window we want to close using the .addAction() method. For example:

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Close Window")
        self.l1=QLabel("Let's Close this Window")
        self.l1.setAlignment(Qt.AlignCenter)
        self.setCentralWidget(self.l1)
        self.exit=QAction("Exit Application",shortcut=QKeySequence("Ctrl+q"),triggered=lambda:self.exit_app)
        self.addAction(self.exit)
    def exit_app(self):
        print("Shortcut pressed") #verification of shortcut press
        self.close()
app=QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()

The above program creates a simple PyQt5 application with a QLabel as its central widget. Then a QAction() is created with some parameters like the name of the action, shortcut and triggered. Where shortcut is the key or key sequence that is needed to be pressed to trigger that action. Also, the triggered parameter is where the function to call on that action being triggered is specified. Then that action is added to the window which needs to be closed using the .addAction() So when the shortcut specified(i.e. Ctrl+q ) is pressed, as expected, the window closes.

Also read:

Digital stopwatch GUI Application in Python – PyQt5

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.

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

Столкнулся с проблемой, что при закрытии главного окна диалоговые не закрываются. Как решить эту проблему?

Пример основного окна:

from PyQt5 import QtCore, QtGui, QtWidgets
import test_dialog


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(150, 140, 75, 23))
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "PushButton"))

class MyWin(QtWidgets.QWidget, Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.pushButton.clicked.connect(lambda: test_dialog.main())


if __name__ == "__main__":
    import sys

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

Диалоговое окно:

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 300)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))

class MyWin(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

def main():
    w = MyWin()
    w.show()
    w.exec_()

Last Updated :
26 Mar, 2020

In this article, we will see how to use close() method which belongs to the QWidget class, this method is used to close the window in PyQt5 application. In other words by close() method the window get closed without manually closing it.

Syntax : self.close()

Argument : It takes no argument.

Code :

from PyQt5.QtWidgets import * 

from PyQt5 import QtCore

from PyQt5 import QtGui

import sys

import time

class Window(QMainWindow):

    def __init__(self):

        super().__init__()

        self.setWindowTitle("Close")

        self.setGeometry(0, 0, 400, 300)

        self.label = QLabel("Icon is set", self)

        self.label.move(100, 100)

        self.label.setStyleSheet("border: 1px solid black;")

        self.show()

        time.sleep(2)

        self.close()

App = QApplication(sys.argv)

window = Window()

sys.exit(App.exec())

This will open the window and after 2 seconds it will automatically closes the window.

Similar Reads

  • clear() method in PyQt5

    While using PyQt5, there occur a need of removing or clearing labels in order to do so clear() method is used. This method belongs to the QLabel class, and can be used on only label widgets. Syntax : label.clear() Argument : It takes no argument. Action Performed : It clears(remove) the label from m


    2 min read

  • deleteLater() method in PyQt5

    While designing an application it could potentially consume a lot of space/memory if care is not taken when closing widgets. The QObject-based classes are designed to be (optionally) linked together in a hierarchy. When a top-level object is deleted, Qt will automatically delete all its child object


    2 min read

  • move() method in PyQt5

    In order to move (changing the position) any widget like buttons or label move() method is used in PyQt5 application. By default, all the widgets are on top left corner therefore, there is a need of changing the position of the widgets. Syntax : move( x, y ) Arguments : It takes two arguments : 1. X


    1 min read

  • setToolTip method in PyQt5

    setToolTip() method is used to setting up a tooltip of a widget in PyqT5 application. A tooltip is a hint in a desktop application (graphical user interface). Tooltips frequently appear when mouse hover over a widget without clicking it. Sometimes, when mouse arrow is held on the button it shows som


    1 min read

  • PyQt5 – rect() method

    rect() method belongs to QtCore.QRect class, this method is used to get the geometry of the window or any widget. It returns the object of type QRect which tells the property of the rectangle. Syntax : widget.rect() Argument : It takes no argument. Return : It returns the rectangle of the widget Cod


    1 min read

  • PyQt5 — isChecked() method for Check Box

    isChecked method is used to know if the check box is checked or not. This method will return true if the check box is checked else it will return false. If we use this method after creating the check box it will always return False as by default check box is not checked. Syntax : checkbox.isChecked(


    2 min read

  • PyQt5 — alignment() method for Label

    In this article, we will see about alignment() method. This method is used to know the type of alignment the label is having. We use setAlignment() method to set the alignment, alignment() method returns the Qt.Alignment object which is the argument of the setAlignment() method. Syntax : label.align


    2 min read

  • PyQt5 — checkState() method for Check Box

    There are basically two states in check box that are checked or unchecked, although using setTristate method we can add an intermediate state. checkState method is used to check the state of the check box, it returns CheckState object but when we print it output will be as follows: 0 for un-checked


    2 min read

  • PyQt5 — isTristate() method for Check Box

    When we create check box in PyQt5 application, by default it has only two states i.e True and False but with the help of setTristate method. isTristate method is used to check if the check box has two states or three states, it return True if check box has three states else it return False. Syntax :


    1 min read

  • PyQt5 — isLeftToRight() method for Check Box

    When we create a check box by default indicator is at left hand side which we call as left to right direction although we can change its direction using setLayoutDirection method. isLeftToRight method is used to check if the layout direction is from left to right or not, it returns True for the defa


    2 min read

PyQt5 — это набор Python-модулей, который позволяет создавать графические интерфейсы пользователя (GUI) для приложений. В PyQt5 имеется несколько способов закрыть окно, в зависимости от требований приложения.

Самый простой способ закрыть окно в PyQt5 — это использовать метод close(). Он вызывается на объекте окна и закрывает его. Пример кода:

window.close()

Другой способ закрыть окно заключается в отправке сигнала «закрытие окна». Сигнал обрабатывается методом, который может выполнить дополнительный код перед закрытием окна. Пример кода:

window.closeEvent = self.closeEvent
def closeEvent(self, event):
# Дополнительный код
super().closeEvent(event)

Третий способ закрыть окно через приложение QApplication. В этом случае используется метод quit(), который закрывает все окна и завершает приложение. Пример кода:

from PyQt5.QtWidgets import QApplication, QMainWindow

app = QApplication([])
main_window = QMainWindow()
main_window.show()
app.exec_()

# Закрыть все окна и выйти из приложения
app.quit()

Описанные выше способы закрытия окна являются наиболее распространенными в PyQt5. Выбор способа зависит от требований вашего приложения.

Как сделать модальное окно на Python, приложение на PyQt6

Как создавать несколько окон в PySide2 — PYTHON

Обновление данных в окне. ООП. Рефакторинг. Создание десктопного приложения с помощью Tkinter #6

Вызов окна на кнопку Pyqt5(PySide2)

Как скрыть окно в Tkinter на Python

Как создать окна в Qt?

Python и PyQt \

Что делать если не закрывается окно(пластиковое)🤷‍♂️

PyQt Диалоговые окна

Изучение PyQT (Python GUI) / Урок #4 – Всплывающие окна (QMessageBox)

BLGPG-93360D8D8938-25-05-05-21

Новые материалы:

  • Линия тренда python
  • Cmap python какие есть
  • Ord обратная функция python
  • Как вывести нечетные числа в python
  • Deque методы python
  • Python word замена текста
  • Курсы python в москве для школьников
  • Как узнать цвет пикселя на экране python
  • End of statement expected python ошибка
  • Как установить библиотеку requests в python на windows
  • Python 44 массивы ответы
  • Напишите программу заказ в макдональдсе с графическим пользовательским интерфейсом на pyqt
  • Почему библиотека numpy работает с массивами быстрее чем обычный интерпретатор python

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как запустить return to castle wolfenstein на windows 10
  • Работа в среде операционной системы microsoft windows
  • Asus windows vista oem
  • Самый лучший медиаплеер для windows 10
  • Клинер для windows 10 официальный сайт