PyQt4在登录后立即启动系统托盘图标

时间:2014-05-07 17:42:55

标签: python qt user-interface pyqt

我正在尝试在成功登录后启动系统托盘菜单。我有2个QtUi屏幕​​,其余的只是python代码。登录对话框首先出现,我想在登录后隐藏它并显示系统托盘菜单。到目前为止,这是我的代码:

注意:UI_Login是来自QtDesigner的对话框

1。系统托盘ui

from PyQt4 import QtGui

class SystemTrayIcon(QtGui.QSystemTrayIcon):

    def __init__(self, icon, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, parent)
        menu = QtGui.QMenu(parent)        
        self.exitAction = menu.addAction("Exit")
        self.helpAction = menu.addAction("Help")
        self.setIcon(icon)
        self.setContextMenu(menu)

2。登录功能。调用SystemTrayIcon

import sys
from PyQt4 import QtGui, QtCore
from modules.ui.login_ui import Ui_Login
from modules.ui.menu_ui import SystemTrayIcon
from api.auth import doLogin

class Login(QtGui.QDialog):
    """
    Login user via the api
    Links the gui and the app functionality
    Logged user token is saved for further processing
    """
    def __init__(self, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.ui = Ui_Login()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.doLogin)

    def doLogin(self):
        self.password = unicode(self.ui.password.text())
        self.email = unicode(self.ui.email.text())      
        request_data = {"username": ""+self.email+"", "password": ""+self.password+""}
        response = doLogin(request_data)

        if response.status_code == 200:
            """ 
                1. Save Api token for future entries
                2. Start app. i.e create a system tray app.
            """
            self.token = response.json()['token'];

            self.hide()
            trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"))
            trayIcon.show()
            print "End check"
        else:
            #Raise error
            print response.json()

第3。主文件

import sys
from PyQt4 import QtGui, QtCore
from modules.login import Login

def main():
    app = QtGui.QApplication(sys.argv)
    login = Login()
    login.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()   

问题 - 登录对话框关闭时,系统托盘图标未显示。

非常感谢您的意见。

2 个答案:

答案 0 :(得分:1)

trayIcon对象是一个局部变量,一旦doLogin()方法完成,就会立即收集垃圾。将其存储为实例属性(例如self.trayIcon)将停止该操作并且您的图标应保持存在。

答案 1 :(得分:0)

QSystemTrayIcon有一个activated信号可以发出。将此信号连接到将创建QMenu

的某种方法
class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, icon, parent=None):
        ...
        self.setContextMenu(menu)
        self.activated.connect(lambda reason: self._create_menu)

    def _create_menu(self):
        menu = QtWidgets.QMenu()
        menu.addAction(QtWidgets.QAction('Quit,None))
        self.setContextMenu(menu)

接下来,您要发出activated信号,以便显示您的菜单。我有一个类似的用例回答here