【问题标题】:closing pyqt messageBox with closeevent of the parent window用父窗口的closeevent关闭pyqt messageBox
【发布时间】:2014-11-11 00:27:22
【问题描述】:

我有以下小菜一碟

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

问题是如果有人关闭了父窗口(即自己),上面的提示就会出现,但是如果有人没有在这个消息框中按是或否,父窗口就不会关闭。

那么当任务完成时我应该如何实现QMessageBox(即回复)也被iteslef关闭,比如调用reply.close()

【问题讨论】:

    标签: python pyqt qmessagebox


    【解决方案1】:

    另一种方式,就是调用bool QWidget.close (self) 来关闭窗口小部件,而不是按窗口中的X 按钮。 (或者在这种情况下调用isFinished)。我们可以覆盖 is close 方法并添加标志来控制QWidget.closeEvent (self, QCloseEvent)。像这样;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      相关资源
      最近更新 更多