12

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?

rolinger
  • 665
  • 7
  • 17
Shahin
  • 1,415
  • 4
  • 22
  • 33
  • 1
    You just have to reimplement the `closeEvent(event)` method in a subclass and minimize the dialog instead of accepting that event. Or do you mean something different? – Bakuriu Sep 11 '12 at 08:50
  • OK, but can you show me some code example? I tried to do something like this, but my program still going to close! – Shahin Sep 11 '12 at 09:04

1 Answers1

26

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
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • Thank you to help me. I found my answer. I don't know why `Qt.WindowMinimized` didn't work for me. I used `self.setVisible(False)` instead of that. Also because I used QDialog, in some window managers, user is capable to close dialog with `Esc key`. then I re implement `done` function and make them same. – Shahin Sep 11 '12 at 12:34
  • 1
    In the documentation they say that the way in which the window state is handled is different on the OSes. On some OS the change isn't instantaneous etc. I tried this solution and worked fine on linux. – Bakuriu Sep 11 '12 at 17:12
  • This closes the main window, how do you prevent it from closing the main application? – jsibs Jul 22 '21 at 23:40