Search code examples
pythonqt4pyqt4contextmenuqwebview

Add items to the standard QWebView context menu


The implementation of QWebView has a standard context menu. I want to change it and create my own - or add "Open in new tab" to the standard context menu, and then connect it to my application. How to do it?


Solution

  • You can reimplement QWebView.contextMenuEvent:

    class WebView(QtWebKit.QWebView):
        def __init__(self, parent=None):
            super(WebView, self).__init__(parent)
            self.newTabAction = QtGui.QAction('Open in new tab', self)
            self.newTabAction.triggered.connect(self.createNewTab)
    
        def createNewTab(self):
            url = self.newTabAction.data()
            print('create new tab:', url.toString())
    
        def contextMenuEvent(self, event):
            menu = self.page().createStandardContextMenu()
            hit = self.page().currentFrame().hitTestContent(event.pos())
            url = hit.linkUrl()
            if url.isValid():
                self.newTabAction.setData(url)
                menu.addAction(self.newTabAction)
            menu.exec_(event.globalPos())
    

    If you don't want to use the standard context menu, just use QtGui.QMenu() to create your own.