Событие Close не обрабатывается при выходе из диалога

У меня есть этот код для закрытия мероприятия

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 в верхней части окна, это не вызывается. Должен ли я подключить этот клик с этой функцией или что-то еще, чтобы он работал

2 ответа

Призвание 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_())

Вы можете реализовать свой собственный фильтр событий

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)
Другие вопросы по тегам