@Salamafet said in [PySide6] QSystemTrayIcon bug when using Class:
I don't understand why, but it works.
Well the reason is that when Python detects nothing is refencing any Python object it destroys it --- that's the object collection the language gices you unlike plain C++.
The mystery is that one would have thought that self.setContextMenu(menu) would itself increment the reference count on menu and its action added to that. I don't know why it does not. I don't know whether menu = QtWidgets.QMenu(self) inside Tray() would have improved the situation. You might like to add that anyway, and then maybe see if the other 2 changes are no longer required.
Ah, see (the C++ explanation for) [void]QSystemTrayIcon::setContextMenu(QMenu *menu) (or PySide6 PySide6.QtWidgets.QSystemTrayIcon.setContextMenu(menu)):
Note: The system tray icon does not take ownership of the menu. You must ensure that it is deleted at the appropriate time by, for example, creating the menu with a suitable parent object.
This explains everything. Whenever it says "something does not take ownership of this QObject" that will mean the Python code will not increment a reference count. setContextMenu() leaves you in charge of the menu, which e.g. you might be using elsewhere. Consequently any QObjects documented like that will require (typically) a Python self._variable = TheObject() to keep it "alive" for the duration of the class instance, not just a local variable. Or, by the looks of it even better, pass self to the top-level object's constructor (your QMenu()) so it is fully owned by the instance.