如何捕获 pyqt closeEvent 并最小化对话框而不是退出? [英] How do I catch a pyqt closeEvent and minimize the dialog instead of exiting?

查看:64
本文介绍了如何捕获 pyqt closeEvent 并最小化对话框而不是退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

class MyDialog(QtGui.QDialog):# ...def __init__(self, parent=None):super(MyDialog, self).__init__(parent)# 当你想销毁对话框时,将此设置为 Trueself._want_to_close = Falsedef closeEvent(self, evnt):如果 self._want_to_close:super(MyDialog, self).closeEvent(evnt)别的:事件.忽略()self.setWindowState(QtCore.Qt.WindowMinimized)

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

<预><代码>>>>从 PyQt4 导入 QtCore、QtGui>>>app = QtGui.QApplication([])>>>赢 = MyDialog()>>>赢.show()>>>app.exec_() #此后尝试关闭对话框,它不会关闭但最小化

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?

解决方案

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

这篇关于如何捕获 pyqt closeEvent 并最小化对话框而不是退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆