如何防止QGraphicsTextItem上的默认上下文菜单?

问题描述 投票:2回答:1

是否可以防止右键单击打开QGraphicsTextItem上的默认上下文菜单?菜单包含“撤消,重做,剪切,复制,粘贴......”。在Ubuntu 18.04上,就是这样。我不知道这在Windows上是如何表现的。

我已经覆盖了鼠标按下处理程序,在我的视图中右键单击并尝试在项目类本身中执行此操作。这实际上确实阻止了Qt 5.10.0上的菜单,但由于某种原因不再在5.11.1

enter image description here

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

    ...
    doOtherHandlingStuff();
    ...
}

在项目本身,如果我这样做,它没有任何影响:

void TextEdit::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
    event->ignore();
    return;
}
c++ qt qt5 qgraphicsview qgraphicsscene
1个回答
3
投票

您必须覆盖QGraphicsTextItem的contextMenuEvent方法:

#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();
}
© www.soinside.com 2019 - 2024. All rights reserved.