如何检测对话框关闭事件?

7


大家好。

我正在使用python3.4和PyQt5在Windows 7上制作GUI应用程序。

这个应用程序非常简单。用户点击主窗口的按钮,信息对话框就会弹出。当用户点击信息对话框的关闭按钮(窗口的X按钮),系统会显示确认消息。就是这样。

以下是我的代码。

# 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_())

结果屏幕截图是...

在这里输入图片描述

在这里输入图片描述

在这种情况下,我已经在mainClass类中添加了这些代码。

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

这段代码仅在主窗口关闭时运行。但是我想让closeEvent函数在childDlg关闭时运行,而不是在主窗口中运行。

我该怎么办?

2个回答

9
您在mainClass类中添加了closeEvent方法。因此,您重新实现了QMainwindowcloseEvent方法而不是childDlgcloseEvent方法。要解决这个问题,您需要像这样对childDlg进行子类化:
# 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_())

3
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.closeEvent = self.CloseEvent

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接