MacOS Pyside2 QSystemTrayIcon, left click/right different functions

659 Views Asked by At

I would like to know how to do in python/Pyside2:

Create a QSystemTrayIcon with a custom icon, in which:

  • If I click left button on it, I do a custom action (just print “left click pressed”). No menu should be shown...

  • If I click right button on it, a context menu appears with an exit action on it, just to close the program.

On MacOS, maybe not in win nor linux, the menu just opens on mouse press... That's why the need of left and right click differentiations otherwise both actions will be done with left and right click. See note here: On macOS... since the menu opens on mouse press

I need help just implementing the left and right click differentiations in the following code:

from PySide2 import QtWidgets
import sys

class SystrayLauncher(object):

    def __init__(self):
        w = QtWidgets.QWidget() #just to get the style(), haven't seen other way
        icon = w.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxInformation)
        self.tray = QtWidgets.QSystemTrayIcon()
        self.tray.setIcon(icon)
        self.tray.setVisible(True)
        self.tray.activated.connect(self.customAction)

        # I JUST WANT TO SEE THE MENU WHEN RIGHT CLICK...
        self.trayIconMenu = QtWidgets.QMenu()
        self.quitAction = QtWidgets.QAction("&Quit", None, triggered=QtWidgets.QApplication.instance().quit)
        self.trayIconMenu.addAction(self.quitAction)
        self.tray.setContextMenu(self.trayIconMenu)

    # JUST WANNA USE THE ACTION WITH LEFT CLICK
    def customAction(self, signal):
        print "left click pressed"

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)

    sl = SystrayLauncher()
    sys.exit(app.exec_())

Can anyone help me, please?

1

There are 1 best solutions below

1
On

you can differentiate the click "reason" and decide what to do. Therefore you will need to add a function like follows:

def right_or_left_click(reason):
    if reason == QSystemTrayIcon.ActivationReason.Trigger:
        print("Left-click detected")
    elif reason == QSystemTrayIcon.ActivationReason.Context:
        print("Right-click detected")
    elif reason == QSystemTrayIcon.ActivationReason.MiddleClick:
        print("Middle-click detected")
    else:
        print("Unknown reason")

self.tray.activated.connect(right_or_left_click)

Then, you can call the desired function on left-click or middle-click. The right-click is occupied by your context menu :)