How to change minimize event behavior in PyQt or P

2019-06-18 08:55发布

I'm developing a Qt application and changed the closing behavior with the closeEvent virtual function this way:

class MainWindow(QMainWindow):
    def closeEvent(self, event):
            event.ignore()
            self.hide()
            self.trayicon.showMessage('Running', 'Running in the background.')

This works as expected. If I remove event.ignore() the application quits as expected, everything is fine.

I want to control the minimize event too, so when the user clicks the minimize button on the title bar, I want to move the window instead of minimize. I cannot use the hideEvent virtual function, because the event will be sent to the window anyway, so this code:

def hideEvent(self, event):
    event.ignore()
    self.move(0,0)

moves the window to the top left AND then minimize it. event.ignore() has no effect here, so I tried using QtCore.QObject.event this way:

def event(self, event):
    if event.type() == QEvent.WindowStateChange:
        if self.isMinimized():
            event.ignore()
            self.move(0,0)
            return True
    return False

The window moves but minimizes again. What is wrong with this ? How can I override the minimize event completely ?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-18 09:26

Try the changeEvent and filter for WindowMinimized events, something like this:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.systemTrayIcon = QtGui.QSystemTrayIcon(self)
        self.systemTrayIcon.setIcon(QtGui.QIcon.fromTheme("face-smile"))
        self.systemTrayIcon.setVisible(True)
        self.systemTrayIcon.activated.connect(self.on_systemTrayIcon_activated)

        self.label = QtGui.QLabel(self)
        self.label.setText("Minimize me!")

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.label)

    @QtCore.pyqtSlot(QtGui.QSystemTrayIcon.ActivationReason)
    def on_systemTrayIcon_activated(self, reason):
        if reason == QtGui.QSystemTrayIcon.DoubleClick:
            if self.isHidden():
                self.show()

            else:
                self.hide()

    def changeEvent(self, event):
        if event.type() == QtCore.QEvent.WindowStateChange:
            if self.windowState() & QtCore.Qt.WindowMinimized:
                event.ignore()
                self.close()
                return

        super(MyWindow, self).changeEvent(event)

    def closeEvent(self, event):
        event.ignore()
        self.hide()
        self.systemTrayIcon.showMessage('Running', 'Running in the background.')

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())
查看更多
登录 后发表回答