c – 在Qt中右键单击事件以打开上下文菜单

前端之家收集整理的这篇文章主要介绍了c – 在Qt中右键单击事件以打开上下文菜单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一段代码调用一个mousePressEvent.我有左键输出光标的坐标,我右键单击相同,但是我也想要右键单击打开一个上下文菜单.我到目前为止的代码是:
  1. void plotspace::mousePressEvent(QMouseEvent*event)
  2. {
  3. double trange = _timeonright - _timeonleft;
  4. int twidth = width();
  5. double tinterval = trange/twidth;
  6.  
  7. int xclicked = event->x();
  8.  
  9. _xvaluecoordinate = _timeonleft+tinterval*xclicked;
  10.  
  11.  
  12.  
  13. double fmax = Data.plane(X,0).max();
  14. double fmin = Data.plane(X,0).min();
  15. double fmargin = (fmax-fmin)/40;
  16. int fheight = height();
  17. double finterval = ((fmax-fmin)+4*fmargin)/fheight;
  18.  
  19. int yclicked = event->y();
  20.  
  21. _yvaluecoordinate = (fmax+fmargin)-finterval*yclicked;
  22.  
  23. cout<<"Time(s): "<<_xvaluecoordinate<<endl;
  24. cout<<"Flux: "<<_yvaluecoordinate<<endl;
  25. cout << "timeonleft= " << _timeonleft << "\n";
  26.  
  27. returncoordinates();
  28.  
  29. emit updateCoordinates();
  30.  
  31. if (event->button()==Qt::RightButton)
  32. {
  33. contextmenu->setContextMenuPolicy(Qt::CustomContextMenu);
  34.  
  35. connect(contextmenu,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(ShowContextMenu(const QPoint&)));
  36.  
  37. void A::ShowContextMenu(const QPoint &pos)
  38. {
  39. QMenu *menu = new QMenu;
  40. menu->addAction(tr("Remove Data Point"),SLOT(test_slot()));
  41.  
  42. menu->exec(w->mapToGlobal(pos));
  43. }
  44.  
  45. }
  46.  
  47. }

我知道我的问题本质上是非常根本的,而且“上下文菜单”没有被正确的声明.我从许多来源拼凑了这个代码,不知道如何在c中声明某些东西.任何建议将不胜感激.

解决方法

当widget的contextMenuPolicy是Qt :: CustomContextMenu,并且用户已经在窗口小部件上请求了一个上下文菜单时,会发出customContextMenuRequested.所以在你的窗口小部件的构造函数中,你可以调用setContextMenuPolicy,并将customContextMenuRequested连接到一个插槽来做一个自定义的上下文菜单.

在绘图空间的构造函数中:

  1. this->setContextMenuPolicy(Qt::CustomContextMenu);
  2.  
  3. connect(this,SIGNAL(customContextMenuRequested(const QPoint &)),SLOT(ShowContextMenu(const QPoint &)));

ShowContextMenu插槽应该是plotspace的类成员,如:

  1. void plotspace::ShowContextMenu(const QPoint &pos)
  2. {
  3. QMenu contextMenu(tr("Context menu"),this);
  4.  
  5. QAction action1("Remove Data Point",this);
  6. connect(&action1,SIGNAL(triggered()),SLOT(removeDataPoint()));
  7. contextMenu.addAction(&action1);
  8.  
  9. contextMenu.exec(mapToGlobal(pos));
  10. }

猜你在找的C&C++相关文章