I am trying to disable a default context menu of QTableView in pyqt.
I have re-implemented the contextMenuEvent but it works on 1st time right click. When I click on the same Item 2nd time the default context menu reappears. (Image attached below for referance.)
I tried "QTableView.setContextMenuPolicy(Qt.NoContextMenu)" but it didn't work. Also referred the answers of similar type questions but still the issue is unresolved.
Any idea?
Ex. showing Re-implemented context menu in QTableView.
def contextMenuEvent(self, event):
menu = QMenu(self)
CutAction = QAction(self.view)
CutAction.setText("&Cut")
menu.addAction(CutAction)
CutAction.setIcon(QIcon(":/{0}.png".format("Cut")))
CutAction.setShortcut("Ctrl+X")
self.connect(CutAction, SIGNAL("triggered()"), self.cut)
with the code that shows I can not reproduce your problem, even so the solution is to use Qt::CustomContextMenu
by enabling the signal customContextMenuRequested
, and in the corresponding slot you have to implement the logic:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class TableView(QTableView):
def __init__(self, *args, **kwargs):
super(TableView, self).__init__(*args, **kwargs)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.onCustomContextMenuRequested)
def onCustomContextMenuRequested(self, pos):
menu = QMenu()
CutAction = menu.addAction("&Cut")
menu.addAction(CutAction)
CutAction.setIcon(QIcon(":/{0}.png".format("Cut")))
CutAction.setShortcut("Ctrl+X")
CutAction.triggered.connect(self.cut)
menu.exec_(self.mapToGlobal(pos))
def cut(self):
pass
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = TableView()
model = QStandardItemModel(10, 10, w)
w.setModel(model)
w.show()
sys.exit(app.exec_())