托盘中的菜单处理程序

时间:2014-06-24 23:52:59

标签: python python-2.7 pyqt pyqt4

我正在尝试在PyQt上编写最简单的应用程序,但得到一个小问题:我不明白为什么在为“退出”面板添加处理程序之后,处理程序没有工作?点击菜单中的“退出”后没有任何反应。我如何解决这个问题,比点击“退出”,我的应用程序将被关闭?

#! /usr/bin/env python
from PyQt4 import QtGui, QtCore

class RightClickMenu(QtGui.QMenu):
    def __init__(self, parent=None):
        iconMenu = QtGui.QMenu.__init__(self, "Edit", parent)
        icon = QtGui.QIcon.fromTheme("edit-cut")
        self.addAction(QtGui.QAction(icon, "&Cut", self))

        icon = QtGui.QIcon.fromTheme("edit-copy")
        self.addAction(QtGui.QAction(icon, "Copy (&X)", self))

        icon = QtGui.QIcon.fromTheme("edit-paste")
        self.addAction(QtGui.QAction(icon, "&Paste", self))

        icon = QtGui.QIcon.fromTheme("edit-paste")
        self.addAction(QtGui.QAction(icon, "&Exit", self))
        self.connect(self, QtCore.SIGNAL('clicked()'), self.exit)

    def exit(self):
        QtCore.QCoreApplication.instance().quit()

class LeftClickMenu(QtGui.QMenu):
    def __init__(self, parent=None):
        QtGui.QMenu.__init__(self, "File", parent)

        icon = QtGui.QIcon.fromTheme("document-new")
        self.addAction(QtGui.QAction(icon, "&New", self))

        icon = QtGui.QIcon.fromTheme("document-open")
        self.addAction(QtGui.QAction(icon, "&Open", self))

        icon = QtGui.QIcon.fromTheme("document-save")
        self.addAction(QtGui.QAction(icon, "&Save", self))

class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, parent)
        self.setIcon(QtGui.QIcon("tray.png"))

        self.right_menu = RightClickMenu()
        self.setContextMenu(self.right_menu)

        self.left_menu = LeftClickMenu()
        self.activated.connect(self.click_trap)

    def click_trap(self, value):
        if value == self.Trigger: #left click!
            self.left_menu.exec_(QtGui.QCursor.pos())

    def welcome(self):
        self.showMessage("Hello", "I should be aware of both buttons")

    def show(self):
        QtGui.QSystemTrayIcon.show(self)
        QtCore.QTimer.singleShot(100, self.welcome)


def main():
    app = QtGui.QApplication([])
    tray = SystemTrayIcon()
    tray.show()
    app.exec_()

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

更改以下行:

self.addAction(QtGui.QAction(icon, "&Exit", self))
self.connect(self, QtCore.SIGNAL('clicked()'), self.exit)

如:

exitAction = QtGui.QAction(icon, "&Exit", self)
self.addAction(exitAction)
exitAction.triggered.connect(self.exit)

问题是您要将clicked QMenu信号连接到exit方法。当您点击操作时,操作的triggered信号不会显示在菜单clicked上,因为操作位于菜单的顶部。

答案 1 :(得分:0)

刚刚改变了这一行

self.addAction(QtGui.QAction(icon, "&Exit", self))
self.connect(self, QtCore.SIGNAL('clicked()'), self.exit)

action = QtGui.QAction(icon, "&Exit", self)
self.addAction(action)
self.connect(action, QtCore.SIGNAL("triggered()"), self.exit)

现在所有伟大的作品!