如何在启动时隐藏 window,只留下托盘图标?

How do hide a window on launch, leaving only the tray icon?

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(),但它在启动时仍然显示空白 window。如果我最小化 window,它就会消失,只留下托盘图标 - 但我怎样才能在启动时自动发生这种情况?

  self.hide()
  self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Tool)

编辑:我在两台装有 Fedora 13 和 CentOS 7 的不同机器上尝试了这段代码

QWidget::hide() 应该做你想做的。问题是您在新实例上调用 show(),这正在撤消构造函数中对 self.hide() 的调用。

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()    # Remove this line
    sys.exit(app.exec_())

解决方案是显示 托盘图标,但隐藏 window。如果我进行以下更改,您的示例适用于 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_())