How to detect dialog closing event?


Hello everybody.

I am making a GUI application using python3.4, PyQt5 on Windows 7.

The app is a very sample. The user presses the button of the main window, a dialog box with information appears. And when the user presses the close button of the information dialog box (button XX), the system displays a confirmation message. It's all.

Here is my code.

# coding: utf-8

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QDialog, QLabel

class mainClass(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        openDlgBtn = QPushButton("openDlg", self)
        openDlgBtn.clicked.connect(self.openChildDialog)
        openDlgBtn.move(50, 50)

        self.setGeometry(100, 100, 200, 200)
        self.show()

    def openChildDialog(self):
        childDlg = QDialog(self)
        childDlgLabel = QLabel("Child dialog", childDlg)

        childDlg.resize(100, 100)
        childDlg.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    mc = mainClass()
    sys.exit(app.exec_())

Result Screen ...

enter image description here

enter image description here

In this situation, I added this code to the mainClass class.

def closeEvent(self, event):
    print("X is clicked")

This code only works when closing the main window. But I want the closeEvent function to work when childDlg closes. Not the main window.

What should I do?

+4
source share
1 answer

, , closeEvent mainClass. , closeOvent QMainwindow, closeEvent childDlg. chilDlg :

# coding: utf-8

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QDialog, QLabel

class ChildDlg(QDialog):
   def closeEvent(self, event):
      print("X is clicked")

class mainClass(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        openDlgBtn = QPushButton("openDlg", self)
        openDlgBtn.clicked.connect(self.openChildDialog)
        openDlgBtn.move(50, 50)

        self.setGeometry(100, 100, 200, 200)
        self.show()

    def openChildDialog(self):
        childDlg = ChildDlg(self)
        childDlgLabel = QLabel("Child dialog", childDlg)

        childDlg.resize(100, 100)
        childDlg.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    mc = mainClass()
    sys.exit(app.exec_())
+6

Source: https://habr.com/ru/post/1623439/


All Articles