edbee / edbee-lib

QWidget based Text Editor Component for Qt. Multi-caret, Textmate grammar and highlighting support.
Other
75 stars 26 forks source link

How to hook into the right-click menu? #65

Closed vadi2 closed 6 years ago

vadi2 commented 6 years ago

How can I add a custom action to the right-click menu? Looking at TextEditorComponent::contextMenuEvent() I don't see a way.

I'd like to add an action to run an indenter on the selected code, for example.

gamecreature commented 6 years ago

There's not yet a very clean way to do it. At the moment in edbee-app. The following is done:

(see: https://github.com/edbee/edbee-app/blob/master/edbee-app/ui/mainwindow.cpp)

edbeeWidget->textEditorComponent()->setContextMenuPolicy( Qt::CustomContextMenu  );
connect( result->textEditorComponent(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(editorContextMenu()) );

Is implemented like this:

/// This method shows a custom editor context menu
void MainWindow::editorContextMenu()
{
    // retrieve the current controller and editor
    edbee::TextEditorWidget* editor = tabEditor();
    if( editor ) {
        edbee::TextEditorController* controller = tabEditor()->controller();

        // create the menu
        QMenu* menu = new QMenu();
        menu->addAction( controller->createAction( "cut", tr("Cut"), QIcon(), menu ) );
        menu->addAction( controller->createAction( "copy", tr("Copy"), QIcon(), menu ) );
        menu->addAction( controller->createAction( "paste", tr("Paste"), QIcon(), menu ) );
        menu->addSeparator();
        menu->addAction( controller->createAction( "sel_all", tr("Select All"), QIcon(), menu ) );

        // is a file coupled to the curent editor add 'reveal in sidebar'
        if( !tabFilename().isEmpty() ) {
            menu->addSeparator();
            menu->addAction( controller->createAction( "app.reveal-in-sidebar", tr("Reveal in Sidebar"), QIcon(), menu ) );
            menu->addAction( action("app.reveal-in-os"));
        }

        /// shows the contextmenu
        menu->exec( QCursor::pos() );

        // delete the menu
        delete menu;
    }
}
vadi2 commented 6 years ago

Thanks!