模拟用户在QSystemTrayIcon中单击

时间:2014-04-23 23:31:21

标签: python qt pyqt trayicon

即使正在执行activated广告位,菜单仍未显示。我通过手动点击托盘图标和模拟点击来跟踪,并通过相同的执行逻辑。

目前我有

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 个答案:

答案 0 :(得分:1)

以下是我如何设置与托盘图标相关联的上下文菜单

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()

似乎您必须在上下文菜单中设置WindowStaysOnTopHint以便显示它。 此解决方案特定于mac,因为它假定任务栏位于顶部。

一个副作用是即使用户点击其他地方,上下文菜单也始终位于顶部。我在上下文菜单上放置了一个事件过滤器,它注册的唯一有用事件是QEvent.Leave