0

当以下代码运行时,托盘应用程序可以在屏幕中间弹出 AboutWindow 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 打开新窗口时的默认行为,当窗口和图标都不共享同一父级时,以及是否有解决此问题的方法。

谢谢。

4

2 回答 2

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

...
于 2011-03-17T12:36:00.630 回答
0

出现此问题是因为当您关闭“唯一”窗口时,Qt 错误地认为您要退出应用程序。您的(Kaos12)答案是一个丑陋的修复恕我直言,有时您真的想关闭这些东西(这与隐藏它不同)。正确的方法是通过添加以下行来禁用此行为:

app.setQuitOnLastWindowClosed(False)

在该代码的第 50 行之后(在“创建”应用程序之后)。该指令将告诉 Qt 即使在所有窗口都关闭时也不要退出应用程序。

于 2013-06-10T21:04:16.853 回答