退出对话框时不处理关闭事件

时间:2013-01-16 23:22:52

标签: python pyqt

我有关闭事件的代码

def closeEvent(self, event):
    print "cloce"
    quit_msg = "Are you sure you want to exit the program?"
    reply = QtGui.QMessageBox.question(self, 'Message',
                 quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

    if reply == QtGui.QMessageBox.Yes:
         event.accept()
    else:
        event.ignore()

但是,当我在窗口顶部的x上移动时,这不会被调用。 我应该用这个函数连接那个klik还是其它的东西,它会起作用

2 个答案:

答案 0 :(得分:1)

调用QDialog::reject ()隐藏对话框而不是关闭它。要在拒绝QDialog之前提示,只需重新实现reject广告位:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtCore, QtGui

class myDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(myDialog, self).__init__(parent)

        self.buttonBox = QtGui.QDialogButtonBox(self)
        self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.msgBox = QtGui.QMessageBox(self) 
        self.msgBox.setText("Are you sure you want to exit the program?")
        self.msgBox.setStandardButtons(QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        self.msgBox.setDefaultButton(QtGui.QMessageBox.Yes)


    @QtCore.pyqtSlot()
    def reject(self):
        msgBoxResult = self.msgBox.exec_()

        if msgBoxResult == QtGui.QMessageBox.Yes:
            return super(myDialog, self).reject()

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('myDialog')

    main = myDialog()
    main.resize(400, 300)
    main.show()

    sys.exit(app.exec_())

答案 1 :(得分:0)

您可以实施自己的事件过滤器

class custom(QWidget):
    def __init__(self):
        super(custom, self).__init__()
        self.installEventFilter(self)

    def eventFilter(self, qobject, qevent):
        qtype = qevent.type()
        if qtype == QEvent.Close:
            qobject.hide()
            return True
        # parents event handler for all other events
        return super(custom,self).eventFilter(qobject, qevent)