2016-03-01 75 views
1
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

我已經在我的問題中說過,我從您發佈的鏈接中獲得了此示例。這個答案並沒有給我我期待的結果。我嘗試了下面的每個答案,這就是爲什麼我在這裏問這個問題。 – Shuman

+0

夠公平的。我已經使鏈接問題更加明顯。也許你還應該說明你的平臺。 – ekhumoro

回答

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_()) 
0

QWidget::hide()應該做你想要什麼。問題是你正在呼叫show()新的實例,這是在構造函數中撤消對self.hide()的調用。

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

剛剛嘗試過,這不起作用。該窗口沒有顯示,但托盤圖標也沒有顯示。因此無法恢復窗口。 – Shuman