pythonqtpyside6qsystemtrayicon

How to add a action to the context menu from a function QSystemTrayIcon


I have tried searching the PySide6 docs for information about the QMenu and QSystemTray classes but I was unable to find any information about adding actions to the context menu from a function. Here is the code that I have tried:

from PySide6.QtWidgets import QSystemTrayIcon, QMenu
from PySide6 import QtWidgets
from PySide6.QtGui import QIcon, QAction
import sys

class MyWidget(QtWidgets.QSystemTrayIcon):
    def __init__(self):
        super().__init__()
        self.trayIcon = QSystemTrayIcon()
        self.trayIcon.setIcon(QIcon("icon.png"))
        self.trayIcon.setVisible(True)
        self.menu = QMenu()
        self.quit = QAction("Quit")
        self.quit.triggered.connect(app.quit)
        self.menu.addAction(self.quit)
        self.menu.updatesEnabled()
        self.menu.setUpdatesEnabled(True)
        self.trayIcon.setContextMenu(self.menu)
        self.trayIcon.activated.connect(self.addMenuAction)
    def addMenuAction(self):
        self.menu.addAction(QAction("Action"))
        self.menu.update()
if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MyWidget()
    widget.show()

    sys.exit(app.exec_())

Solution

  • The problem is that the QAction you create does not have ownership so it will be destroyed instantly since it is a local variable. There are 2 options:

    action = QAction("Action", self)
    self.menu.addAction(action)
    

    OR

    action = self.menu.addAction("Action")