点击菜单项

时间:2016-06-20 09:38:38

标签: python pyqt

我是python和pyqt的新手,今天我学习它们并编写一个小型系统托盘恶魔, 它运行,但当我点击“约”,然后关闭对话框,应用程序退出。 我不知道为什么

简单代码如下:

import sys
from PyQt4 import QtGui

class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, icon, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, icon, parent)
        self.menu = QtGui.QMenu(parent)

        # about action
        aboutAction = QtGui.QAction("About", self)
        aboutAction.triggered.connect(self.about_fun)
        self.menu.addAction(aboutAction)

        # quit action
        quitAction = QtGui.QAction("Quit", self)
        quitAction.triggered.connect(self.quit_fun)
        self.menu.addAction(quitAction)

        #
        self.setContextMenu(self.menu)

        # listen activated
        self.activated.connect(self.iconActivated)

    def about_fun(self):
        QtGui.QMessageBox.about(self.parent(), "about", "pyqt system tray")

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

    def iconActivated(self, reason):
        if reason == QtGui.QSystemTrayIcon.Trigger:
            print 'left click: TODO'

def main():
    app = QtGui.QApplication(sys.argv)
    trayIcon = SystemTrayIcon(QtGui.QIcon("trash.svg"))
    trayIcon.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:3)

您可以将应用程序quitOnLastWindowClosed属性设置为False:

def main():
    app = QtGui.QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)
    trayIcon = SystemTrayIcon(QtGui.QIcon("trash.svg"))
    trayIcon.show()
    sys.exit(app.exec_())