如何使用QT中的EventFilter单击菜单选项右键单击菜单选项?
我有一个qgraphicsview
,其中包含许多qgraphicsItem
。如果我单击鼠标右键单击任何qgraphicSitem
,则该项目应获得选择和正确的菜单选项,然后我将选择其中一个选项。 通过它,我使用contextMenu
右键单击菜单。右键单击菜单正在正确地进行。但是,我没有得到如何将它们连接到某种功能的方法,以便我可以为其编写逻辑。
这意味着,如果我单击保存
选项,特定的qgraphicsItem
应该选择,我应该能够转到某个功能,我将写逻辑以保存。
bool myClass::eventFilter(QObject *watched, QEvent *event)
{
switch(event->type())
{
case QEvent::ContextMenu:
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*> (event);
menu = new QMenu(this);
option = menu->addMenu("CopyOption");
option->addAction("save");
menu->exec(mouseEvent->globalPos());
break;
}
default:
break;
}
}
I have a QGraphicsView
which contains many QGraphicsItem
. If I click mouse right click on any QGraphicsItem
, the item should get select and right menu options should appear and then I will choose one of the options among them.To do that I have installed eventFilter
and through it, I am using ContextMenu
to create right click menu. Right click menu are getting cretaed properly. But propblem is I am not getting how to connect them to some function so that I can write logic for it.
It means if I clicked on save
option that particular QGraphicsItem
should get select and I should be able to go to some function where I will write logic for saving.
bool myClass::eventFilter(QObject *watched, QEvent *event)
{
switch(event->type())
{
case QEvent::ContextMenu:
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*> (event);
menu = new QMenu(this);
option = menu->addMenu("CopyOption");
option->addAction("save");
menu->exec(mouseEvent->globalPos());
break;
}
default:
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的方法中,当您没有选择任何项目时,您将显示上下文菜单。这是相当糟糕的主意。您不想在视图的任何位置显示上下文菜单。您必须检查光标鼠标是否在项目上。
为什么不从
qgraphicsItem
派生,而OrderloadMousePressEvent
方法。在此方法中,检查鼠标的右键是否单击。如果是这样,请显示上下文菜单并单击哪个操作。最小代码将是:检查的所有工作是在鼠标下进行的所有项目均由QT完成,
MousePressEvent
仅在必要时才调用。QgraphicsView上的另一种方法是覆盖
MousePressEvent
。在其中:qgraphicSitem
具有iSunderMouse
方法qmenu
并显示其qaction
,如果是保存
调用做保存并标记为选定的项目的正确方法In your approach you show a context menu when you have no information if any item is selected. It is rather bad idea. You don't want to show the context menu in any location of view. You have to check if a cursor mouse is over an item.
Why not to derive from
QGraphicsItem
and just overloadmousePressEvent
method. Inside this method check if right button of mouse is clicked. If so, show context menu and test which action is clicked. Minimal code would be:All the job with checking is an item is under mouse is done by QT,
mousePressEvent
is invoked only if it is necessary.Another approach would be override
mousePressEvent
on QGraphicsView. Inside which:QGraphicsItem
hasisUnderMouse
methodQMenu
and show itQAction
, if it issave
call a proper method which doing the save and mark the item as selected