16

I am using a TrayIcon, I have added a "Exit" QAction, and now, I want to execute a certain function when clicking Exit in the TrayIcon menu. Here is the code I have :

class TrayIcon(QSystemTrayIcon):
    """
    Displays a system tray icon
    """

    def __init__(self, interface: Interface) -> None:
        """
        Constructor
        :param interface: Interface to show when the tray icon is clicked
        """
        super().__init__(QIcon(resource_filename("ezstorage.resources.img.tray_icon", "folder.png")))
        self.interface = interface
        self.setVisible(True)
        self.show()
        self.activated.connect(self.clicked)
        menu = QMenu()
        action = QAction("Exit")
        menu.addAction(action)
        self.setContextMenu(menu)

2 Answers 2

32

This is how I'd connect icons in the menu to functions according to your code:

self.menu = QMenu()
self.action = QAction("Exit")
self.menu.addAction(self.action)
self.action.triggered.connect(self.my_function)

The function self.my_function then does whatever you'd like to have.

1
5
def setupTrayIcon(self, MainWindow):
    self.tray_icon = QSystemTrayIcon()
    self.tray_icon.setIcon(QIcon("logo.png"))
    self.tray_icon.setToolTip("System Tray Management")
    self.tray_icon.show()
    self.tray_icon.tray_menu = QtWidgets.QMenu()
def setupActions(self,MainWindow):
    self.tray_icon.show_action = QtWidgets.QAction("Show", MainWindow)
    self.tray_icon.quit_action = QtWidgets.QAction("Exit", MainWindow)
    self.tray_icon.hide_action = QtWidgets.QAction("Hide", MainWindow)
    self.tray_icon.tray_menu.addAction(self.tray_icon.show_action)
    self.tray_icon.tray_menu.addAction(self.tray_icon.hide_action)
    self.tray_icon.tray_menu.addAction(self.tray_icon.quit_action)
    self.tray_icon.setContextMenu(self.tray_icon.tray_menu)
def ConnectAction(self, MainWindow):
    self.tray_icon.show_action.triggered.connect(self.handleShowAction)
    self.tray_icon.hide_action.triggered.connect(self.handleTrayIconButton)
    self.tray_icon.quit_action.triggered.connect(self.close_application)

This show how it works in a MainWindow Class. Ps. you need to implement the methods to be called, when clicking the actions. In my case they are called (self.handleShowAction, self.handleTrayIconButton and self.close_application).

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.