如何检测对话框的关闭事件? [英] How to detect dialog's close event?

查看:45
本文介绍了如何检测对话框的关闭事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


大家好.

我正在 Windows 7 中使用 python3.4、PyQt5 制作 GUI 应用程序.

I am making a GUI application using python3.4, PyQt5 in windows 7.

应用程序非常示例.用户单击主窗口的按钮,弹出信息对话框.当用户点击信息对话框的关闭按钮(窗口的 X 按钮)时,系统显示确认信息.这就是全部.

Application is very sample. User clicks a main window's button, information dialog pops up. And when a user clicks information dialog's close button (window's X button), system shows confirm message. This is all.

这是我的代码.

# 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 类中添加了这些代码.

In this situation, I've added these code in mainClass class.

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

此代码仅在主窗口关闭时有效.但我想要的是 closeEvent 函数在 childDlg 关闭时起作用.不是主窗口.

This code works only when the main window is closed. But what I want is closeEvent function works when childDlg is to closed. Not main window.

我该怎么办?

推荐答案

您在 mainClass 类中添加了方法 closeEvent.因此,您重新实现了 QMainwindow 的方法 closeEvent 而不是 childDlg 的方法 closeEvent.为此,您必须像这样将 childDlg 子类化:

You have added, the method closeEvent in the class mainClass. So you have reimplemented the method closeEvent of your QMainwindow and not the method closeEvent of your childDlg. To do it, you have to subclass your chilDlg like this:

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

这篇关于如何检测对话框的关闭事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆