第二十篇 -- 重写关闭窗口函数

平常关闭窗口只需要点击右上方那个叉叉就可以了,但是有时候写程序时,需要在关闭窗口时进行其他的操作,这样就需要我们对closeEvent函数重写。比如写一个最简单的弹窗。

效果图:

可以看到不管是点击关闭按钮,还是点击主窗口自带的关闭按钮,都出现了弹窗。当然,你也可以在函数里面做一些其他的操作,根据自己的需要。

rewrite_close.py

#!/usr/bin/env python
# _*_ coding: UTF-8 _*_
"""=================================================
@Project -> File    : Operate_system_ModeView_structure -> rewite_close.py
@IDE     : PyCharm
@Author  : zihan
@Date    : 2020/4/29 16:30
@Desc    :
================================================="""
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from ui_close import Ui_MainWindow


class QmyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)  # 调用父类构造函数
        self.ui = Ui_MainWindow()  # 创建UI对象
        self.ui.setupUi(self)  # 构造UI

        # # ===================由connectSlotsByName()自动关联的槽函数
        self.ui.Btn_Close.clicked.connect(self.do_btn_close)

    def closeEvent(self, event):
        defaultBtn = QMessageBox.NoButton
        result = QMessageBox.question(self, "Question", "Are you sure exist ?", QMessageBox.Yes | QMessageBox.No, defaultBtn)
        if result == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def do_btn_close(self):
        self.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)  # 创建app
    form = QmyMainWindow()
    form.show()
    sys.exit(app.exec_())

至于图形界面的代码就不附上了,自己随便画一个图就行了。

原文地址:https://www.cnblogs.com/smart-zihan/p/12803139.html