我正在开发一个Qt应用程序并用这种方式改变了closeEvent
virtual function的关闭行为:
class MainWindow(QMainWindow): def closeEvent(self, event): event.ignore() self.hide() self.trayicon.showMessage('Running', 'Running in the background.')
这按预期工作.如果我删除event.ignore()应用程序按预期退出,一切都很好.
我也想控制最小化事件,所以当用户点击标题栏上的最小化按钮时,我想移动窗口而不是最小化.
我无法使用hideEvent
虚函数,因为无论如何事件都会被发送到窗口,所以这段代码:
def hideEvent(self, event): event.ignore() self.move(0,0)
将窗口移动到左上角然后将其最小化. event.ignore()在这里没有效果,所以我尝试用这种方式使用QtCore.QObject.event
:
def event(self, event): if event.type() == QEvent.WindowStateChange: if self.isMinimized(): event.ignore() self.move(0,0) return True return False
窗口移动但最小化.这有什么问题?如何完全覆盖最小化事件?
解决方法:
尝试changeEvent
并过滤WindowMinimized
事件,如下所示:
#!/usr/bin/env python#-*- coding:utf-8 -*-from PyQt4 import QtGui, QtCoreclass 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_())
来源:http://www.icode9.com/content-4-199401.html
联系客服