closing pyqt messageBox with closeevent of the parent window

你。 提交于 2019-12-12 09:23:09

问题


I have folllowing piece of cake

def __init__():
    self._taskInProgress = threading.Event()


def isFinished(self):
    self._taskInProgress.clear()
    self.progressBar.hide()
    self.close()


def closeEvent(self, event):
    if self._taskInProgress.is_set():
        reply = QtGui.QMessageBox.question(self, "Are you sure you want to quit? ",
            "Task is in progress !",
            QtGui.QMessageBox.Yes,
            QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

the problem is if somebody closes the parent window(i.e. self) the above prompt shows up , but if somebody doesn't press yes or no in this message box the parent window doesn't closes.

So how should I achieve that when task finishes the QMessageBox (i.e. reply) is also closed by iteslef, like calling reply.close()


回答1:


Another way, It's exactly to call bool QWidget.close (self) to close widget by not press X button in window. (Or in this case is call isFinished). We can override is close method and add flag to control QWidget.closeEvent (self, QCloseEvent). Like this;

import sys
from PyQt4 import QtCore, QtGui

class QCsMainWindow (QtGui.QMainWindow):
    def __init__ (self):
        super(QCsMainWindow, self).__init__()
        self.isDirectlyClose = False
        QtCore.QTimer.singleShot(5 * 1000, self.close) # For simulate test direct close 

    def close (self):
        for childQWidget in self.findChildren(QtGui.QWidget):
            childQWidget.close()
        self.isDirectlyClose = True
        return QtGui.QMainWindow.close(self)

    def closeEvent (self, eventQCloseEvent):
        if self.isDirectlyClose:
            eventQCloseEvent.accept()
        else:
            answer = QtGui.QMessageBox.question (
                self,
                'Are you sure you want to quit ?',
                'Task is in progress !',
                QtGui.QMessageBox.Yes,
                QtGui.QMessageBox.No)
            if (answer == QtGui.QMessageBox.Yes) or (self.isDirectlyClose == True):
                eventQCloseEvent.accept()
            else:
                eventQCloseEvent.ignore()

appQApplication = QtGui.QApplication(sys.argv)
mainQWidget = QCsMainWindow()
mainQWidget.show()
sys.exit(appQApplication.exec_())


来源:https://stackoverflow.com/questions/25882595/closing-pyqt-messagebox-with-closeevent-of-the-parent-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!