【发布时间】:2016-03-01 22:57:10
【问题描述】:
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 尝试了这段代码
【问题讨论】:
-
我已经在我的问题中说过,我从您发布的链接中获得了这个示例。这个答案并没有给我我正在寻找的结果。我尝试了它下面的每个答案,这就是我在这里提出问题的原因。
-
很公平。我已经使链接的问题更加明显。也许您还应该说明您在哪个平台上。
标签: python pyqt minimize trayicon