Maxwe11
Maxwe11

Reputation: 107

Pyqt5 Right click and open in new tab

I have qwebengine that i have overwritten its context menu with a custom pop up menu and i am need to add menu item that when i right click a url it gives me the option to open in new tab, how i can achieve this? I have no idea how to do it so i have no code to show and there isn't enough topics out there but in qt simple broswer they have the below code but it's not understood for me as i never worked with qt here is the example:

void WebView::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu *menu = page()->createStandardContextMenu();
    const QList<QAction*> actions = menu->actions();
    auto it = std::find(actions.cbegin(), actions.cend(), page()->action(QWebEnginePage::OpenLinkInThisWindow));
    if (it != actions.cend()) {
        (*it)->setText(tr("Open Link in This Tab"));
        ++it;
        QAction *before(it == actions.cend() ? nullptr : *it);
        menu->insertAction(before, page()->action(QWebEnginePage::OpenLinkInNewWindow));
        menu->insertAction(before, page()->action(QWebEnginePage::OpenLinkInNewTab));
    }
    menu->popup(event->globalPos());
} 

If someone can explain the above code and provide simple snippet on how i can achieve it in pyqt, I would be so thankful.

Upvotes: 0

Views: 1617

Answers (2)

Shi
Shi

Reputation: 91

If a link was right-clicked, use the following snippet to get the address:

self.page().contextMenuData().linkUrl()

where self is a QWebEngineView. You can call isEmpty() on the url to test whether it was actually a link that was right-clicked.

Upvotes: 2

Nimish Bansal
Nimish Bansal

Reputation: 1759

self.yourWidget_qwebengine.contextMenuEvent=self.mycontextMenuEvent

def mycontextMenuEvent(self, event):
        menu = QtWidgets.QMenu(self)
        oneAction = menu.addAction("&Open New Tab")
        twoAction = menu.addAction("O&pen in New Window")
        menu.exec_(event.globalPos())

Adding this simple code might help if you have overwritten context menu event

Upvotes: 2

Related Questions