Search code examples
pythonqt5pyside2

QSystemTrayIcon change Icon


I'm trying to change / update the icon of a QSystemtrayIcon but it won't work.

main.py:

if __name__=="__main__":

app = QApplication(sys.argv)

from systray import SystemTrayIcon
trayIcon = SystemTrayIcon(parent=app)
trayIcon.show()

sys.exit(app.exec_())

systray.py:

class SystemTrayIcon(QSystemTrayIcon):

def __init__(self, parent=None):
    QSystemTrayIcon.__init__(self, parent)
    icon = QIcon(abspath("images/icon.png"))
    self.setIcon(icon)
    #menu stuff and so on

def set_icon(self):
    self.setIcon(QIcon(abspath("images/envelope.png")))

Inside my mainwindow.py i want to change the icon when an event occurs. How do i call the set_icon mehtod or change the icon right from mainwindow.py?

Thanks alot

Edit:

I tried following in mainwindow.py:

import systray

class MainWindow(QWidget):
    #class stuff

    def change_icon(self):
        trayIcon = systray.SystemTrayIcon()
        trayIcon.set_icon()

The function is called, when i put a print inside set_icon in systray its printed, but it wont change the icon.

Any suggestions?


Solution

  • The problem as I see in your code is that in the mainwindow.py you are creating another SystemTrayIcon that is a local variable that as you say calls the function set_icon correctly but since it is a local variable it is eliminated when it is finished running set_icon, so that will not be seen.

    A possible solution is to pass it to systray in the constructor and make it a member of the class:

    mainwindow.py

    from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton
    
    class MainWindow(QWidget):
        def __init__(self, systray, parent=None):
            QWidget.__init__(self, parent)
            lay = QVBoxLayout(self)
            self.button = QPushButton("Change Icon")
            lay.addWidget(self.button)
            self.systray = systray
    
            self.button.clicked.connect(self.systray.set_icon)
    

    systray.py

    from os.path import abspath
    
    from PyQt5.QtWidgets import QSystemTrayIcon
    from PyQt5.QtGui import QIcon
    
    
    class SystemTrayIcon(QSystemTrayIcon):
        def __init__(self, parent=None):
            QSystemTrayIcon.__init__(self, parent)
            icon = QIcon(abspath("images/icon.png"))
            self.setIcon(icon)
    
        def set_icon(self):
            self.setIcon(QIcon(abspath("images/envelope.png")))
    

    main.py

    import sys
    
    from PyQt5.QtWidgets import QApplication
    
    from mainwindow import MainWindow
    from systray import SystemTrayIcon
    
    
    if __name__=="__main__":
    
        app = QApplication(sys.argv)
    
        systray = SystemTrayIcon(app)
        systray.show()
        w = MainWindow(systray)
        w.show()
        sys.exit(app.exec_())