Search code examples
c++qtqt5qgraphicsviewqgraphicsscene

How to prevent default context menu on QGraphicsTextItem?


Is it possible to prevent right-click from opening the default context menu on QGraphicsTextItem ? The menu with "Undo, Redo, Cut, Copy, Paste..". On Ubuntu 18.04, that is. I don't know how this behaves on Windows.

I have overridden the mouse press handler to eat right-clicks in my view and tried to do that also in the item class itself. This actually did prevent the menu on Qt 5.10.0, but for some reason not anymore on 5.11.1:

enter image description here

void EditorView::mousePressEvent(QMouseEvent * event)
{ 
    if (event->button() == Qt::RightButton)
    {
        return;
    }

    ...
    doOtherHandlingStuff();
    ...
}

In the item itself it doesn't have any effect if I do this:

void TextEdit::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
    event->ignore();
    return;
}

Solution

  • You have to override the contextMenuEvent method of QGraphicsTextItem:

    #include <QtWidgets>
    
    class GraphicsTextItem: public QGraphicsTextItem
    {
    public:
        using QGraphicsTextItem::QGraphicsTextItem;
    protected:
        void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override
        {
            event->ignore();
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QGraphicsScene scene;
        QGraphicsView w{&scene};
        auto it = new GraphicsTextItem("Hello World");
        it->setTextInteractionFlags(Qt::TextEditable);
        scene.addItem(it);
        w.show();
        return a.exec();
    }