Search code examples
c++qtcontextmenuqplaintextedit

Adding event to the context menu in QPlainTextEdit


context_menu_now

This is my Context Menu after right click on QPlainTextEdit. I want to add function to load data from file in Context Menu. Can I? How?


Solution

  • Method 1: QPlainTextEdit::contextMenuEvent

    You should override the QPlainTextEdit::contextMenuEvent as mentioned in the Qt documentation:

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

    You can connect the QAction::triggered signal to your method (slot) to load the data or you can use one of the QMenu::addAction overloads, which allows you to specify a slot directly.

    If you do not want to subclass QPlainTextEdit (to override contextMenuEvent), you can use event filtering in Qt.

    Note that contextMenuEvent() is only called when contextMenuPolicy is not set (or set to its default value Qt::DefaultContextMenu)

    Method 2: QWidget::customContextMenuRequested

    As an alternative, you can use Qt's signal and slot mechanism to create the context menu when requested by the user.

    The contextMenuPolicy property should be set to Qt::CustomContextMenu, in which case the QWidget::customContextMenuRequested signal is invoked whenever a context menu is requested by the user. This signal should be connected to your own slot, which should create the context menu as shown in the code above (Method 1).

    Using MyQPlainTextEdit in Qt Designer

    To use your MyQPlainTextEdit in a .ui file, you should implement it as a promoted QPlainTextEdit and use it in your .ui file instead of a regular QPlainTextEdit. See the Qt documentation for more information.

    To be able to use your class in the Qt Designer, you should not forget to implement a constructor accepting a parent QWidget as is done in the AnalogClock example. Note that implementing such a constructor is always a good idea, because Qt typically manages ownership through a child-parent relationship.