0

I would like to intercept the paste action of a QLineEdit context menu that is created by default in any QLineEdit widget (see picture below)

enter image description here

Is there a way to redirect the Paste action of the context menu by any means?

Woltan
  • 13,723
  • 15
  • 78
  • 104

1 Answers1

1

One can fiddle with the actions in the context menu by overloading the contextMenuEvent of the QLineEdit widget.

Edit:

The code of the link above:

void LineEdit::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu *menu = createStandardContextMenu();
    menu->addAction(tr("My Menu Item"));
    //...
    menu->exec(event->globalPos());
    delete menu;
}

And the code that I actually used for my purposes:

menu = self.createStandardContextMenu()

menu.actions()[5].connect(self.paste) # The hard ref to the 6th item is not ideal but what can you do...

menu.exec_(event.globalPos())
Woltan
  • 13,723
  • 15
  • 78
  • 104
  • You could also use `createStandardContextMenu()`: `void LineEdit::contextMenuEvent(QContextMenuEvent *event) { QMenu *menu = createStandardContextMenu(); QAction *action = menu->exec(event->globalPos()); if(action->text().compare("&Paste\tCtrl+V") == 0){ qDebug()<<"test"; } }` – eyllanesc Aug 10 '17 at 11:55
  • @eyllanesc That is correct. Out of completeness I edited my answer to show the complete code. – Woltan Aug 11 '17 at 06:56
  • 1
    A better way to handle connecting the action would be to create an action first, connect it's 'triggered' slot and then add it into the menu. This also allows you to index it into the context menu wherever you want. I proposed an edit to your post :) – Spencer Sep 27 '18 at 21:20