Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Context Menu



  • Hi, I would like to change the standard context menu of QTextEdit. I've tried in the following way, but nothing happens:

    void notepad::contextMenuEvent(QContextMenuEvent *){
        QMenu *menu = ui->textEdit->createStandardContextMenu();
        menu->clear(); 
        menu->addAction("Save");  
        menu->addAction("Export to Pdf");
    }
    


  • @Martinuccia_96 You didn't show the menu...Use menu->popup(e->globalPos()) to show it.
    (As @JonB 's answer, exec() is easier for deleting the menu after it is done showing, I usually use popup() when it doesn't need to be deleted.)
    And if you use menu->clear() then no need to call createStandardContextMenu().
    You can create a menu as member variable, add actions in the constructor and just show it in the event.



  • @Martinuccia_96
    You have to actually show the menu you have created! Just follow the example at https://doc.qt.io/qt-5/qtextedit.html#contextMenuEvent :

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


  • @Bonnie said in Context Menu:

    (As @JonB 's answer, exec() is easier for deleting the menu after it is done showing, I usually use popup() when it doesn't need to be deleted.)

    Hi @Bonnie. You know I totally respect your answers, they are excellent, so I don't want to nitpick, but as someone said about this to you in another post the other day, doesn't it bother you that if you do it that way and with new QMenu(this) then you leave a new menu instance in existence every time the user clicks, which don't get deleted till you kill of the this?



  • @JonB Yes, I agreed with that. So I didn't argue.
    I was just expressing a concept that time, not the full code.
    Usually if I use new QMenu(this) everytime a menu shows, I'll add setAttribute(Qt::WA_DeleteOnClose) to it.
    This time, when I'm saying "doesn't need to be deleted", I mean the menu may be a member variable that can be used repeatedly and does not need to be deleted in every event.



  • @Bonnie said in Context Menu:

    Usually if I use new QMenu(this) everytime a menu shows, I'll add setAttribute(Qt::WA_DeleteOnClose) to it.

    That's fine, that's what I wanted to know. Armed with that, I may be happier using popup() now! I had been thinking in term of having to add a deleteLater() on whatever "close" signal popup() (presumably) emits, this is much neater :)


Log in to reply