Context Menu does not appear on tray icon when I click with mouse

Asked

Viewed 30 times

0

I’m creating an app that has a tray icon (QSystemTrayIcon) and I want him to have some options to control the application. For this I created the class below:

class QTrayIcon(object):

    def __init__(self, title, icon, parent = None):
        self.__trayIcon = QSystemTrayIcon(parent = parent)
        self.__context_menu = QMenu()
        self.__trayIcon.setContextMenu(self.__context_menu)

        self.set_icon(icon)
        self.set_title(title)

    def add_option(self, text, function):
        option = QAction(text)
        option.triggered.connect(function)
        self.__context_menu.addAction(option)

    def set_icon(self, icon):
        self.__icon = QIcon(icon)
        self.__trayIcon.setIcon(self.__icon)
        self.__trayIcon.setVisible(True)

    def set_title(self, title):
        self.__trayIcon.setToolTip(title)

The tray icon is created normally. The problem is that when I right-click to open the "context menu", nothing happens. Or rather, you can notice a very small dot - about 2 pixels - appearing and disappearing quickly. Below is the sample code to run the class:

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QAction, QMenu, QSystemTrayIcon, QApplication
import sys

application = QApplication(sys.argv)
tray = QTrayIcon("Application name", "My icon.ico", application)
tray.add_option("Primeira opção", lambda: None)
tray.add_option("Segunda opção", lambda: None)
application.exec_()

What am I doing wrong? I’ve reviewed the class several times and can’t see any mistake.

1 answer

0


The problem is that the objects of QAction, at the end of the method execution, they lose their references and are collected by the Garbage Collector.

To solve the problem, you must instantiate each of the objects in order to maintain their reference. In your case, store each object in a list. See the code below:

class QTrayIcon(object):

    __options = []

    def __init__(self, title, icon, parent = None):
        self.__trayIcon = QSystemTrayIcon(parent = parent)
        self.__context_menu = QMenu()
        self.__trayIcon.setContextMenu(self.__context_menu)

        self.set_icon(icon)
        self.set_title(title)

    def add_option(self, text, function):
        option = QAction(text)
        option.triggered.connect(function)
        self.__context_menu.addAction(option)
        self.__options.append(option)

    def set_icon(self, icon):
        self.__icon = QIcon(icon)
        self.__trayIcon.setIcon(self.__icon)
        self.__trayIcon.setVisible(True)

    def set_title(self, title):
        self.__trayIcon.setToolTip(title)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.