I write a class TrayIcon inherit QSystemTrayIcon, why I can't call show() directly, `TrayIcon().show()`.

Qt Code:
  1. # It works:
  2. # my_tray_icon = TrayIcon(my_widget)
  3. # my_tray_icon.show()
  4.  
  5. # But why doesn't this work? The icon does not appear in the system tray.
  6. TrayIcon(my_widget).show()
To copy to clipboard, switch view to plain text mode 


Qt Code:
  1. import sys
  2.  
  3. from PySide2.QtGui import QIcon
  4. from PySide2.QtWidgets import QSystemTrayIcon, QAction, QMenu, QApplication, QWidget, qApp
  5.  
  6. # from PyQt5.QtGui import QIcon
  7. # from PyQt5.QtWidgets import QSystemTrayIcon, QAction, QMenu, QApplication, QWidget, qApp
  8.  
  9. class TrayIcon(QSystemTrayIcon):
  10. def __init__(self, app):
  11. super().__init__()
  12. self.app = app
  13. self.setIcon(QIcon('icon.png'))
  14. self.activated.connect(self.icon_activated)
  15. self.tray_menu = QMenu(QApplication.desktop())
  16. self.show_action = QAction('&show')
  17. self.quit_action = QAction('&exit')
  18. self.show_action.triggered.connect(app.show)
  19. self.quit_action.triggered.connect(qApp.quit)
  20. self.tray_menu.addAction(self.show_action)
  21. self.tray_menu.addAction(self.quit_action)
  22. self.setContextMenu(self.tray_menu)
  23.  
  24. def icon_activated(self, reason):
  25. if reason in (QSystemTrayIcon.Trigger, QSystemTrayIcon.DoubleClick):
  26. self.app.show()
  27. # for Windows
  28. self.app.activateWindow()
  29. # for macOS
  30. self.app.raise_()
  31.  
  32.  
  33. def main():
  34. app = QApplication(sys.argv)
  35. app.setQuitOnLastWindowClosed(False)
  36. my_widget = QWidget()
  37.  
  38. # It works:
  39. # my_tray_icon = TrayIcon(my_widget)
  40. # my_tray_icon.show()
  41.  
  42. # But why doesn't this work? The icon does not appear in the system tray.
  43. TrayIcon(my_widget).show()
  44.  
  45. sys.exit(app.exec_())
  46.  
  47.  
  48. if __name__ == '__main__':
  49. main()
To copy to clipboard, switch view to plain text mode