Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt - Connect QAction to function

Tags:

python

pyqt

pyqt5

I am using a TrayIcon, I have added a "Exit" QAction, and now, I want to execute a certain function when clicking Exit in the TrayIcon menu. Here is the code I have :

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)
like image 798
Rémy Kaloustian Avatar asked May 31 '17 09:05

Rémy Kaloustian


2 Answers

This is how I'd connect icons in the menu to functions according to your code:

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

The function self.my_function then does whatever you'd like to have.

like image 185
Christoph Engwer Avatar answered Sep 17 '22 19:09

Christoph Engwer


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)

This show how it works in a MainWindow Class. Ps. you need to implement the methods to be called, when clicking the actions. In my case they are called (self.handleShowAction, self.handleTrayIconButton and self.close_application).

like image 42
Ole Avatar answered Sep 17 '22 19:09

Ole