如何在 PyQt 或 PySide 中更改最小化事件行为? [英] How to change minimize event behavior in PyQt or PySide?
问题描述
我正在开发 Qt 应用程序并使用 closeEvent
虚函数 这样:
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.')
这按预期工作.如果我删除 event.ignore()
应用程序按预期退出,一切都很好.
This works as expected. If I remove event.ignore()
the application quits as expected, everything is fine.
我也想控制最小化事件,所以当用户点击标题栏上的最小化按钮时,我想移动窗口而不是最小化.我不能使用 hideEvent
虚函数,因为事件无论如何都会发送到窗口,所以这段代码:
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)
将窗口移动到左上角,然后将其最小化.event.ignore()
在这里没有效果,所以我尝试使用 QtCore.QObject.event
这样:
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 ?
推荐答案
试试 changeEvent
并过滤WindowMinimized
事件,类似这样:
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_())
这篇关于如何在 PyQt 或 PySide 中更改最小化事件行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!