PyQt5: Can QAction function be triggered via QPushButton

1k views Asked by At

I have created a right-click menu function where all the right-click functions are linked to a QAction

Eg:

self.contextMenu = QtWidgets.QMenu(self)
self.contextMenu.addAction(self.actionAdd_Data)
self.pushButton.customContextMenuRequested.connect(self.initContextMenu)

def initContextMenu(self, event):
    action = self.contextMenu.exec_(self.pushButton.mapToGlobal(event))
    if action == self.actionAdd_Data:
        print("Do something")

Is it possible that I can emulate clicking on the right-click button? Something like pushButton.click() but for the QAction instead.

I have tried

self.pushButton2.clicked.connect(self.actionAdd_Data.trigger)

But nothing happens.

Can anyone help? Thanks.

1

There are 1 answers

0
musicamante On BEST ANSWER

While using the returned action from QMenu.exec_() works fine for menus created "on the fly", the general (and preferred) usage of a QAction is to do something when their triggered() signal is emitted.

This allows to keep a single QAction that always does what it's been created for, while being able to add that action anywhere it's needed (could it be a menu, a tool bar, or even a keyboard shortcut) without constantly checking if that action has been triggered.

In the following example, the addData() function is called both when it's activated from the menu and when someOtherButton is clicked.

        self.actionAdd_Data = QAction('Add data', self)
        self.actionAdd_Data.triggered.connect(self.addData)
        self.contextMenu.addAction(self.actionAdd_Data)
        # ...
        self.someOtherButton.clicked.connect(self.actionAdd_Data.trigger)


    def initContextMenu(self, pos):
        self.contextMenu.exec_(self.pushButton.mapToGlobal(pos))

    def addData(self):
        # do something