PDA

View Full Version : Adding actions to a context menu



aarelovich
6th October 2009, 16:50
Hello Everybody:

Simple problem here. I use a QPlainTextEdit to do a simple code editor. Now the text edit allready has a standard right-click-contex-menu and I want to add two actions (comment and uncomment). However with the code I found on the web:


action_comment = new QAction("Comment",this);
this->addAction(action_comment);
this->setContextMenuPolicy(Qt::ActionsContextMenu);

And this works but all the default options disappear and only comment appears. What I want to know is, Is there any way to add actions to the default context menu or do I have to create one from scratch if I want more actions?

Thanks for any help

jpn
6th October 2009, 16:56
See QPlainTextEdit::createStandardContextMenu

aarelovich
6th October 2009, 17:13
Hi:

Sorry to bother again, but I did found a solution. I reimplemented the contextMenuEvent with this code:



void CodeEditor::contextMenuEvent(QContextMenuEvent *event){
QMenu *menu = this->createStandardContextMenu();
menu->addAction(action_comment);
menu->addAction(action_uncomment);
menu->insertSeparator(action_comment);
menu->exec(event->globalPos());
}


action_comment/uncomment were two private objects which are created and connected in the constructor to their respective code.

I'm posting it in case it helps anyone.

spirit
6th October 2009, 18:27
you could also use QWidget::customContextMenuRequested and QWdiget::setContextMenuPolicy with Qt::CustomContextMenu.

zeFree
7th December 2011, 13:47
a better "working" and tested example is here:
http://www.qtcentre.org/threads/35166-extend-the-standard-context-menu-of-qtextedit

I hope I have helped! :)