How do I catch a pyqt closeEvent and minimize the dialog instead of exiting?

流过昼夜 提交于 2019-12-09 11:28:38

问题


I have a QDialog object. When the user clicks on the X button or presses Ctrl+Q, I want the dialog to go to a minimized view or system tray icon, instead of closing. How do I do that?


回答1:


A simple subclass that minimizes instead of closing is the following:

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)

You can test it with this snippet in the interactive interpreter:

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


来源:https://stackoverflow.com/questions/12365202/how-do-i-catch-a-pyqt-closeevent-and-minimize-the-dialog-instead-of-exiting

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