2011-03-15 75 views
0

當以下代碼運行時,托盤應用程序可以在屏幕中間彈出AboutWindow QLabel對象。但是,當關閉此屏幕時,整個應用程序將無故障關閉(托盤圖標消失,控制檯日誌顯示無任何錯誤)。PyQt4托盤圖標顯示QLabel時出現問題

import sys 
from PyQt4 import QtGui, QtCore 


class AboutWindow(QtGui.QLabel): 

def __init__(self, parent=None): 
    QtGui.QLabel.__init__(self, parent=parent) 
    self.setText(""" 
    Huge text goes here 
    """) 


class SystemTrayIcon(QtGui.QSystemTrayIcon): 
    def __init__(self, icon, parent=None): 
     QtGui.QSystemTrayIcon.__init__(self, icon, parent) 
     menu = QtGui.QMenu(parent) 
     self.createMenuActions(menu) 
     self.setContextMenu(menu) 
     # I've tried using the same parent as QSystemTrayIcon, 
     # but the label is not shown. 
     # self.aboutWindow = AboutWindow(parent=parent) 
     self.aboutWindow = AboutWindow(parent=None) 


    def createMenuActions(self, menu): 
     exitAction = QtGui.QAction("Exit", menu) 
     configureAppAction = QtGui.QAction("Configure Application", menu) 
     aboutAction = QtGui.QAction("About", menu) 

     self.connect(configureAppAction, QtCore.SIGNAL('triggered()'), self._configureApp) 
     self.connect(aboutAction, QtCore.SIGNAL('triggered()'), self._showAbout) 
     self.connect(exitAction, QtCore.SIGNAL('triggered()'), self._exitApp) 

     self.addActionsToMenu(menu, configureAppAction, aboutAction, exitAction) 

    def addActionsToMenu(self, menu, *args): 
     for action in args: 
      menu.addAction(action) 

    def _configureApp(self): pass 

    def _showAbout(self): 
     self.aboutWindow.show() 

    def _exitApp(self): 
     sys.exit(0) 

def main(): 
    app = QtGui.QApplication(sys.argv) 
    widget = QtGui.QWidget() 
    # I'm passing a widget parent to QSystemTrayIcon as pointed out in: 
    # http://stackoverflow.com/questions/893984/pyqt-show-menu-in-a-system-tray-application 
    trayIcon = SystemTrayIcon(QtGui.QIcon("icon.xpm"), widget) 
    trayIcon.show() 
    sys.exit(app.exec_()) 

if __name__ == '__main__': 
    main() 

如上代碼中指出,我已經嘗試設置托盤圖標和AboutWindow對象相同的父,但沒有工作(沒有顯示標籤)。我也嘗試了繼承QMainWindow,但同樣的效果發生。

我想知道,如果這是從QSystemTrayIcon打開一個新窗口,當窗口和圖標共享同一父,並且如果有解決此問題的方法時的默認行爲。

謝謝。

回答

0

好的,我想我對這個問題不太清楚,但是我找到了一個簡單的解決方案。

Qt有一個捕獲關閉事件的方法,該關閉事件被分派到一個小部件(http://doc.qt.nokia.com/4.6/qwidget.html#closeEvent)。你可以在你的QWidget子類中重寫這個方法來阻止這個小部件關閉(在我的所有測試中,這將關閉整個應用程序)並且只隱藏它。下面的代碼顯示了我在我的代碼已經改變,使其工作:發生

... 

class AboutWindow(QtGui.QLabel): 

    def __init__(self, parent=None): 
     QtGui.QLabel.__init__(self, parent=parent) 
     self.setText(""" 
     Huge text goes here 
     """) 

    # Prevent the widget from closing the whole application, only hides it 
    def closeEvent(self, event): 
     event.ignore() 
     self.hide() 

... 
0

此問題,因爲當您關閉「唯一」窗口,Qt的誤認爲你想退出應用程序。 你的(Kaos12)答案是一個醜陋的修復恕我直言,有時你真的想關閉的東西(這是不一樣的隱藏它)。 做正確的方法是通過將線禁用此行爲:

app.setQuitOnLastWindowClosed(False) 

在該代碼的第50行之後(「建立」該應用程序之後)。這條指令會告訴Qt即使所有窗口關閉都不會退出應用程序。