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