【问题标题】:PyQt - Connect QAction to functionPyQt - 将 QAction 连接到函数
【发布时间】:2017-11-01 01:22:09
【问题描述】:

我正在使用 TrayIcon,我添加了一个“退出”QAction,现在,我想在单击 TrayIcon 菜单中的退出时执行某个功能。这是我的代码:

class TrayIcon(QSystemTrayIcon):
    """
    Displays a system tray icon
    """

    def __init__(self, interface: Interface) -> None:
        """
        Constructor
        :param interface: Interface to show when the tray icon is clicked
        """
        super().__init__(QIcon(resource_filename("ezstorage.resources.img.tray_icon", "folder.png")))
        self.interface = interface
        self.setVisible(True)
        self.show()
        self.activated.connect(self.clicked)
        menu = QMenu()
        action = QAction("Exit")
        menu.addAction(action)
        self.setContextMenu(menu)

【问题讨论】:

    标签: python pyqt pyqt5


    【解决方案1】:

    这就是我根据您的代码将菜单中的图标连接到功能的方式:

    self.menu = QMenu()
    self.action = QAction("Exit")
    self.menu.addAction(self.action)
    self.action.triggered.connect(self.my_function)
    

    函数self.my_function 然后做任何你想做的事情。

    【讨论】:

    • 谢谢。谢谢克里斯托夫。
    【解决方案2】:
    def setupTrayIcon(self, MainWindow):
        self.tray_icon = QSystemTrayIcon()
        self.tray_icon.setIcon(QIcon("logo.png"))
        self.tray_icon.setToolTip("System Tray Management")
        self.tray_icon.show()
        self.tray_icon.tray_menu = QtWidgets.QMenu()
    def setupActions(self,MainWindow):
        self.tray_icon.show_action = QtWidgets.QAction("Show", MainWindow)
        self.tray_icon.quit_action = QtWidgets.QAction("Exit", MainWindow)
        self.tray_icon.hide_action = QtWidgets.QAction("Hide", MainWindow)
        self.tray_icon.tray_menu.addAction(self.tray_icon.show_action)
        self.tray_icon.tray_menu.addAction(self.tray_icon.hide_action)
        self.tray_icon.tray_menu.addAction(self.tray_icon.quit_action)
        self.tray_icon.setContextMenu(self.tray_icon.tray_menu)
    def ConnectAction(self, MainWindow):
        self.tray_icon.show_action.triggered.connect(self.handleShowAction)
        self.tray_icon.hide_action.triggered.connect(self.handleTrayIconButton)
        self.tray_icon.quit_action.triggered.connect(self.close_application)
    

    这显示了它在 MainWindow 类中的工作方式。 附言。单击操作时,您需要实现要调用的方法。在我的例子中,它们被称为(self.handleShowAction、self.handleTrayIconButton 和 self.close_application)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多