在PyQt5中如何控制Windows关闭按钮事件?

时间:2018-02-05 10:39:31

标签: python pyqt5

如果用户确定在按下Windows关闭按钮时关闭应用程序,我想做出选择吗?到目前为止,我已经对此进行了编码,这提示应用程序即将退出,但我无法捕获该事件或让应用程序等待用户确认。我对此很陌生,任何人都可以帮忙。 这是我的代码,

from PyQt5 import QtCore, QtGui, QtWidgets
import sys

class Ui_MainWindow(object):


    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        ##
        #......some more codes
        ##
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        app.aboutToQuit.connect(self.closeEvent)


    def retranslateUi(self, MainWindow):
        ## codes



    def closeEvent(self):
        print("User has clicked the red x on the main window")
        ## HERE I WANT TO GIVE AN OPTION TO THE USER IF THEY REALLY WANT TO QUIT
        ## AND ON THIS TIME THE MAIN APP/ MAIN WINDOW NEEDS TO BE ON AS IT IS


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

This post描述了应该如何做。

简而言之,这是furas

的答案

(我使用PyQt4.QtGui,但我认为这与此应用程序的PyQt5.QtWidgets完全相同)

import sys

from PyQt4.QtGui import QApplication, QMessageBox, QMainWindow, QAction


class  Ui_MainWindow(QMainWindow):
    def __init__(self):

        QMainWindow.__init__(self)

    def setupUI(self):


        self.setGeometry(500, 300, 700, 700)

        self.setWindowTitle("window")


        finish = QAction("Quit", self)
        finish.triggered.connect(self.closeEvent)

        menubar = self.menuBar()
        fmenu = menubar.addMenu("File")
        fmenu.addAction(finish)

    def retranslateUi(self):
        ## codes
        codes = "___"


    def closeEvent(self, event):
        close = QMessageBox.question(self,
                                     "QUIT",
                                     "Sure?",
                                      QMessageBox.Yes | QMessageBox.No)
        if close == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Ui_MainWindow()
    window.setupUI()
    window.show()
    sys.exit(app.exec_())