How to create a context menu
-
I want a context menu to work with a specific TableWidget but when I click anywhere in the application the context menu pops up. Below is the code I tried, Please I need assistance of how to get this done.
def contextMenuEvent(self, event): contextMenu = QMenu(self) addAction = contextMenu.addAction("Add New") editAction = contextMenu.addAction("Edit") deleteAction = contextMenu.addAction("Delete") action = contextMenu.exec_(self.mapToGlobal(event.pos())) if action == editAction: self.updatePersonID() self.Info_Updatesearch() if action == deleteAction: self.singleClick_searchDelete() if action == addAction: self.ui.stackedWidget.setCurrentWidget(self.ui.personalInformation_page)
-
@LT-K101
I really ought not have to do this, you should know this, it is common sense.If you want
customContextMenuRequested
signal to be raised you have to tell widget to do so when you set up the connection:self.ui.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.tableWidget.customContextMenuRequested.connect(self.openMenu)
-
@LT-K101 said in How to create a context menu:
def contextMenuEvent(self, event)
I guess this is in your main window (you did not mention this)?
You need to subclass QTableWidget and override contextMenuEvent there...
Or do it in main window but check which widget is under the mouse cursor and only show pop-up if it is over your table widget. -
@jsulm I tried the code below but it does not seem working , I think am doing something wrong.
self.ui.tableWidget.customContextMenuRequested.connect(openMenu) def openMenu(self, position): self.ui.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu) menu = QMenu() editAction = menu.addAction('Edit') action = menu.exec_(self.ui.tableWidget.mapToGlobal(position)) if action == editAction: self.ui.stackedWidget.setCurrentWidget(self.ui.personalInformation_editpage) self.ui.tableWidget.show()
-
@LT-K101 said in How to create a context menu:
self.ui.tableWidget.customContextMenuRequested.connect(openMenu)
You should look at and show the error message!
openMenu()
is a method in a class. So:self.ui.tableWidget.customContextMenuRequested.connect(self.openMenu)
-
@LT-K101
Since you setself.ui.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
only insidedef openMenu()
, how do you expect theself.ui.tableWidget.customContextMenuRequested
signal to be raised to callself.openMenu()
in the first place? -
@LT-K101
I really ought not have to do this, you should know this, it is common sense.If you want
customContextMenuRequested
signal to be raised you have to tell widget to do so when you set up the connection:self.ui.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.tableWidget.customContextMenuRequested.connect(self.openMenu)