Simulate user clicking in QSystemTrayIcon

混江龙づ霸主 提交于 2019-12-02 08:47:31

问题


Even through the activated slot is being executed, the menu is still not showing. I traced through manually clicking the tray icon and the simulated click, and its going through the same execution logic.

Currently I have

class MyClass(QObject):
   def __init__():
       self._testSignal.connect(self._test_show)
       self.myTrayIcon.activated.connect(lambda reason: self._update_menu_and_show(reason))

   def show():
       self._testSignal.emit()

   @pyqtSlot()
   def _test_show():
       self._trayIcon.activated.emit(QtWidgets.QSystemTrayIcon.Trigger)

   @QtCore.pyqtSlot()
   def _update_menu_and_show(reason):
       if reason in (QtWidgets.QSystemTrayIcon.Trigger):
        mySystemTrayIcon._update_menu()

...
class MySystemTrayIcon(QSystemTrayIcon):

   def _update_menu(self):
      # logic to populate menu
      self.setContextMenu(menu)
...
MyClass().show()

回答1:


Here is how I made the context menu associated with the tray icon pop up

class MyClass(QObject):
   def __init__():
       self._testSignal.connect(self._test_show)
       self.myTrayIcon.activated.connect(lambda reason: self._update_menu_and_show(reason))

   def show():
       self._testSignal.emit()

   @pyqtSlot()
   def _test_show():
       self._trayIcon.activated.emit(QSystemTrayIcon.Context)

   @QtCore.pyqtSlot()
   def _update_menu_and_show(reason):
       if reason in (QSystemTrayIcon.Trigger, QSystemTrayIcon.Context):
           mySystemTrayIcon._update_menu()
           # Trigger means user initiated, Context used for simulated
           # if simulated seems like we have to tell the window to explicitly show

           if reason == QSystemTrayIcon.Context:
               mySystemTrayIcon.contextMenu().setWindowFlags(QtCore.Qt.WindowStaysOnTopHint|QtCore.Qt.FramelessWindowHint)
               pos = mySystemTrayIcon.geometry().bottomLeft()
               mySystemTrayIcon.contextMenu().move(pos)
               mySystemTrayIcon.contextMenu().show()

...
class MySystemTrayIcon(QSystemTrayIcon):

   def _update_menu(self):
      # logic to populate menu
      self.setContextMenu(menu)
...
MyClass().show()

It seems you have to set the WindowStaysOnTopHint on the context menu so that it will appear. This solution is specific to mac since it assumes the taskbar is on the top.

One side effect is that the context menu is always on top, even if the user clicks somewhere else. I placed an event filter on the context menu, the only useful event that it registered was QEvent.Leave



来源:https://stackoverflow.com/questions/23257052/simulate-user-clicking-in-qsystemtrayicon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!