我试图在成功登录后启动系统托盘菜单。我有2个qui屏幕,其余的只是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()
-登录对话框关闭时系统托盘图标不显示
trayIcon
对象是一个局部变量,一旦doLogin()
方法完成,它立即被垃圾收集。将其存储为实例属性(如self.trayIcon
)将停止,你的图标应该保持存在。
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
信号,以便您的菜单将显示。我有一个类似的用例,这里有答案。