如何捕获pyqt closeEvent并最小化对话框而不是退出?

时间:2012-09-11 07:56:27

标签: python pyqt pyqt4 qdialog

我有一个QDialog对象。当用户点击X按钮或按Ctrl+Q时,我希望对话框转到最小化视图或系统托盘图标,而不是关闭。我怎么做?

1 个答案:

答案 0 :(得分:16)

最小化而不是关闭的简单子类如下:

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

        # when you want to destroy the dialog set this to True
        self._want_to_close = False

    def closeEvent(self, evnt):
        if self._want_to_close:
            super(MyDialog, self).closeEvent(evnt)
        else:
            evnt.ignore()
            self.setWindowState(QtCore.Qt.WindowMinimized)

您可以在交互式解释器中使用此代码段对其进行测试:

>>> from PyQt4 import QtCore, QtGui
>>> app = QtGui.QApplication([])
>>> win = MyDialog()
>>> win.show()
>>> app.exec_()   #after this try to close the dialog, it wont close bu minimize