How to catch pyqt closeEvent and minimize the dialog, rather than exit?

I have a QDialog object. When the user presses the X button or press Ctrl+Q , I want the dialog box to switch to a miniature view or icon in the system tray, and not to close. How can I do it?

+7
source share
1 answer

A simple subclass that collapses instead of closing is this:

 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 
+14
source

All Articles