2

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)

enter image description here

1 Answer 1

1

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_())
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the reply.....I tried the above code but my custom context menu is disappeared and default menu is still there.
@String39 Have you tried my code or have you adapted it to your code?
I tried your code but default menu is still there. Also my custom context menu is disappeared.
@String39 What version of PyQt4 do you have?
I have installed PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x32.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.