QMenu for a tray icon doesn't show

Hi,

I’m trying to create a mouse right-click menu for a QSysTrayIcon, but the menu doesn’t show.

What I do is this:

def create_tray_icon(self):
    # Create the application instance
    self.app = QApplication(sys.argv)
    self.icon = QSystemTrayIcon()
    self.icon.setIcon(QIcon("MyIcon.ico"))
    self.icon.setToolTip(f"Row1\nRow2\n"
                         f"Row3")

    # Create a context menu for the tray icon
    menu = QMenu()

    # Add a "Quit" option to the menu
    quit_action = QAction("Quit")
    quit_action.triggered.connect(self.app.quit)
    menu.addAction(quit_action)

    # Set the context menu for the tray icon
    self.icon.setContextMenu(menu)

    # Show the tray icon
    self.icon.show()

The tray icon shows, the tooltip, too, but if I right click the icon I don’t see the Quit option.

I’m on windows 11

What am I doing wrong?

Thanks

For me this one work:

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


def main():
    app = QApplication(sys.argv)
    tray_icon = QSystemTrayIcon()
    # Replace with a valid icon path
    tray_icon.setIcon(QIcon("C:\\Users\\user1\\Projects\\dcspy\\src\\dcspy.ico"))

    # Main tray menu
    tray_menu = QMenu()
    exit_action = QAction("Exit")
    exit_action.triggered.connect(app.quit)
    tray_menu.addAction(exit_action)

    tray_icon.setContextMenu(tray_menu)
    tray_icon.show()

    sys.exit(app.exec())


if __name__ == "__main__":
    main()

@sandman42
If I remove self, add my icon and add sys.exit(app.exec()) your code woking in my machine… can open menu and quit app…

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

def create_tray_icon():
    # Create the application instance
    app = QApplication(sys.argv)
    icon = QSystemTrayIcon()
    icon.setIcon(QIcon("C:\\Users\\user1\\Projects\\dcspy\\src\\dcspy.ico"))
    icon.setToolTip(f"Row1\nRow2\nRow3")

    # Create a context menu for the tray icon
    menu = QMenu()

    # Add a "Quit" option to the menu
    quit_action = QAction("Quit")
    quit_action.triggered.connect(app.quit)
    menu.addAction(quit_action)

    # Set the context menu for the tray icon
    icon.setContextMenu(menu)

    # Show the tray icon
    icon.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    create_tray_icon()

It works. Thanks a lot

1 Like