我有一段调用mousePressEvent的代码。我有左键单击输出光标的坐标,我有右键单击做同样的,但我也想右键单击打开上下文菜单。我到目前为止的代码是:
void plotspace::mousePressEvent(QMouseEvent*event)
{
double trange = _timeonright - _timeonleft;
int twidth = width();
double tinterval = trange/twidth;
int xclicked = event->x();
_xvaluecoordinate = _timeonleft+tinterval*xclicked;
double fmax = Data.plane(X,0).max();
double fmin = Data.plane(X,0).min();
double fmargin = (fmax-fmin)/40;
int fheight = height();
double finterval = ((fmax-fmin)+4*fmargin)/fheight;
int yclicked = event->y();
_yvaluecoordinate = (fmax+fmargin)-finterval*yclicked;
cout<<"Time(s): "<<_xvaluecoordinate<<endl;
cout<<"Flux: "<<_yvaluecoordinate<<endl;
cout << "timeonleft= " << _timeonleft << "\n";
returncoordinates();
emit updateCoordinates();
if (event->button()==Qt::RightButton)
{
contextmenu->setContextMenuPolicy(Qt::CustomContextMenu);
connect(contextmenu, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(ShowContextMenu(const QPoint&)));
void A::ShowContextMenu(const QPoint &pos)
{
QMenu *menu = new QMenu;
menu->addAction(tr("Remove Data Point"), this,
SLOT(test_slot()));
menu->exec(w->mapToGlobal(pos));
}
}
}
我知道我的问题本质上是非常根本的,并且'contextmenu'没有被正确宣布。我已将来自许多来源的代码拼凑在一起,并且不知道如何在c ++中声明某些东西。任何建议都将不胜感激。
答案 0 :(得分:38)
customContextMenuRequested
时,会发出 Qt::CustomContextMenu
,并且用户已在窗口小部件上请求了上下文菜单。因此,在窗口小部件的构造函数中,您可以调用setContextMenuPolicy
并将customContextMenuRequested
连接到插槽以创建自定义上下文菜单。
在plotspace
的构造函数中:
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(ShowContextMenu(const QPoint &)));
ShowContextMenu
广告位应该是plotspace
的类成员,例如:
void plotspace::ShowContextMenu(const QPoint &pos)
{
QMenu contextMenu(tr("Context menu"), this);
QAction action1("Remove Data Point", this);
connect(&action1, SIGNAL(triggered()), this, SLOT(removeDataPoint()));
contextMenu.addAction(&action1);
contextMenu.exec(mapToGlobal(pos));
}