Is there a way to execute a function when a QSystemTrayIcon is clicked?

155 Views Asked by At

I have a QSystemTrayIcon, and I want to execute a function when left clicking on it and right clicking on it. Is there a way to do so? Thanks.

Here is my code, my class Trail (not derived from QSystemTrayIcon, but it's okay)

app = _qt.QApplication(sys.argv)
mainwindow = None
# mainwindow is defined just before calling a new Trail object, don't worry

class Trail :
    def __init__(self,win) :
        self.mainwindow = win

    def reopen(self) :
        try :
            self.mainwindow.show()
            app.setActiveWindow(self.mainwindow)
        except Exception as e :
            utils.functions.alert("Erreur","Erreur, impossible de réouvrir l'application ("+str(e)+")")

    def close_tray(self) :
        self.tray.setVisible(False)
        os._exit(0)

    def on_clicked(self) :
        print("Test")

    def call(self) :
        try :
            self.icon = _qt.QIcon(utils.vars.ressources_dir+"logo-min-white.png")

            # Adding item on the menu bar
            self.tray = _qt.QSystemTrayIcon()
            self.tray.setIcon(self.icon)
            self.tray.setVisible(True)

            # Creating the options
            self.menu = _qt.QMenu()
            self.option1 = _qt.QAction("Rouvrir")
            self.option1.triggered.connect( self.reopen )
            self.menu.addAction(self.option1)
            self.menu.addSeparator()

            # To quit the app
            self.quitter = _qt.QAction("Quitter l'application")
            self.quitter.triggered.connect( self.close_tray )
            self.menu.addAction(self.quitter)

            # Adding options to the System Tray
            self.tray.setContextMenu(self.menu)
            self.tray.trigger(self.on_clicked)
        except Exception as e :
            print("Erreur lors du lancement du trail : "+str(e))
1

There are 1 best solutions below

0
On BEST ANSWER

(see @scopchanov's comment)

Okay, great, I found the solution :

Just after

self.menu = _qt.QMenu()

I added

self.menu.aboutToShow.connect(self.myAwesomeFunctionWhenRightClickingOnTheTray)

And now, if I right click on my tray, my function is executed just before showing the actual menu !

Thanks @scopchanov !

(I searched "QSystemTrayIcon activated signal example pyqt" on google, and that worked... Before, I wasn't searching for the good thing.)