Here's an example I've made that anyone can run, you will need to replace self.path_to_tray_image to a path of an image in order for it to actually appear in the system tray.
self.path_to_tray_image = "C:/Users/username/Downloads/image.png"
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QSystemTrayIcon, QMenu
from PyQt6.QtCore import QPoint
from PyQt6.QtGui import QIcon, QAction, QCursor
class TrayApplication(QMainWindow):
def __init__(self):
# replace to your tray image
self.path_to_tray_image = "C:/Users/username/Downloads/image.png"
super().__init__()
self.setWindowTitle("Tray Example")
self.setGeometry(100, 100, 400, 300)
# Create a button to minimize to tray
self.minimize_button = QPushButton("Minimize to Tray", self)
self.minimize_button.setGeometry(150, 120, 100, 40)
self.minimize_button.clicked.connect(self.minimize_to_tray)
# Set up the system tray icon
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(QIcon(self.path_to_tray_image)) # Replace with your icon file
# Add a context menu to the tray icon
self.tray_menu = QMenu()
quit_action = QAction(QIcon(":/path_to_exit_action_image"), "Quit", self) # Replace with your icon file
quit_action.triggered.connect(self.close_application)
self.tray_menu.addAction(quit_action)
# Connect the tray icon activation event
self.tray_icon.activated.connect(self.tray_icon_clicked)
def minimize_to_tray(self):
self.hide()
self.tray_icon.show()
def restore_from_tray(self):
self.show()
self.tray_icon.hide()
def tray_icon_clicked(self, reason):
# Left click
if reason == QSystemTrayIcon.ActivationReason.Trigger:
self.restore_from_tray()
# Right click
elif reason == QSystemTrayIcon.ActivationReason.Context:
# Get the current cursor position
cursor_pos = QCursor.pos()
# Calculate the menu position: align bottom-right corner of the menu to the cursor
menu_width = self.tray_menu.sizeHint().width()
menu_height = self.tray_menu.sizeHint().height()
pos = QPoint(cursor_pos.x() - menu_width, cursor_pos.y() - menu_height)
# Show the menu at the calculated position
self.tray_menu.popup(pos)
def close_application(self):
self.tray_icon.hide()
self.close()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = TrayApplication()
window.show()
sys.exit(app.exec())