Michael Bergmann
Michael Bergmann

Reputation: 85

QScintilla: How to add a user context menu to textEdit? (C++)

I'm struggeling with telling a QScitilla textEdit that is the main widget of my MainWindow app to accept showing a personalized context menu on right-clicking the mouse.

What works fine if I use a standard Qt5 textEdit fails if used with the QScintilla alternative. I tried it with defining a user menu from some actions:

void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu(this);
    menu.addAction(cutAct);
    menu.addAction(copyAct);
    menu.addAction(pasteAct);
    menu.exec(event->globalPos());
}
#endif // QT_NO_CONTEXTMENU

reacting on QContextMenuEvent, but the menu only shows up when I right-click an element of the MainWindow instead of the QScintilla textEdit. When I do within the textEdit, only the standard cut/copy/paste menu is shown.

How to implement that for QScintilla textEdit?

Upvotes: 1

Views: 654

Answers (1)

tunglt
tunglt

Reputation: 1072

There are two methods:

Method 1: set Qt::CustomContextMenu for context menu policy of QScintilla text edit :

    textEdit->setContextMenuPolicy( Qt::CustomContextMenu );
    connect(textEdit, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(ShowContextMenu(const QPoint &)));

}

void MainWindow::ShowContextMenu(const QPoint &pos)
{
    QMenu contextMenu(tr("Context menu"), this);

    QAction action1("Action 1", this);
    connect(&action1, &QAction::triggered, this, []{
        qDebug() << "On action 1 click !!!";
    });

    contextMenu.addAction(&action1);
    contextMenu.exec(mapToGlobal(pos));
}

Method 2: Define a subclass of QScintilla then redefine the override function contextMenuEvent :

class MyQsciScintilla : public QsciScintilla
{
    Q_OBJECT
public:
    explicit MyQsciScintilla(QWidget *parent = nullptr);
    void contextMenuEvent(QContextMenuEvent *event);
    //....
};

void MyQsciScintilla::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu *menu = createStandardContextMenu();

    menu->addAction(tr("My Menu Item"));
    //...
    menu->exec(event->globalPos());
    delete menu;
}

Upvotes: 1

Related Questions