import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
style = self.style()
# Set the window and tray icon to something
icon = style.standardIcon(QtGui.QStyle.SP_MediaSeekForward)
self.tray_icon = QtGui.QSystemTrayIcon()
self.tray_icon.setIcon(QtGui.QIcon(icon))
self.setWindowIcon(QtGui.QIcon(icon))
# Restore the window when the tray icon is double clicked.
self.tray_icon.activated.connect(self.restore_window)
# why this doesn't work?
self.hide()
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Tool)
def event(self, event):
if (event.type() == QtCore.QEvent.WindowStateChange and
self.isMinimized()):
# The window is already minimized at this point. AFAIK,
# there is no hook stop a minimize event. Instead,
# removing the Qt.Tool flag should remove the window
# from the taskbar.
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Tool)
self.tray_icon.show()
return True
else:
return super(Example, self).event(event)
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(
self,
'Message',"Are you sure to quit?",
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
self.tray_icon.show()
self.hide()
event.ignore()
def restore_window(self, reason):
if reason == QtGui.QSystemTrayIcon.DoubleClick:
self.tray_icon.hide()
# self.showNormal will restore the window even if it was
# minimized.
self.showNormal()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
我想让它只在启动时显示托盘图标,示例来自此处:
我将以下内容添加到initUI()
,但仍然在启动时显示一个空白窗口。如果我最小化窗口,它会消失,只留下托盘图标 - 但是如何在启动时自动实现这一点?
self.hide()
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Tool)
编辑:我在两台使用Fedora 13和CentOS 7
的不同机器上尝试了这段代码答案 0 :(得分:1)
解决方案是显示托盘图标,但隐藏窗口。如果我进行以下更改,您的示例适用于Windows:
def initUI(self):
...
self.hide()
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Tool)
# explicitly show the tray-icon
self.tray_icon.show()
def main():
...
ex = Example()
# don't re-show the window!
# ex.show()
sys.exit(app.exec_())
答案 1 :(得分:0)
show()
应该做你想做的事。问题是您在新实例上调用self.hide()
,该实例正在撤消构造函数中对def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show() # Remove this line
sys.exit(app.exec_())
的调用。
{{1}}