ahl*_*481 16 c++ events qt contextmenu
我有一段调用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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我的问题本质上是非常基本的,并且'contextmenu'没有被正确宣布.我已将来自许多来源的代码拼凑在一起,并且不知道如何在c ++中声明某些东西.任何建议将不胜感激.
Nej*_*jat 42
customContextMenuRequested在窗口小部件的contextMenuPolicy是Qt::CustomContextMenu,并且用户已在窗口小部件上请求上下文菜单时发出.因此,在窗口小部件的构造函数中,您可以调用setContextMenuPolicy并连接customContextMenuRequested到插槽以创建自定义上下文菜单.
在以下构造函数中plotspace:
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(ShowContextMenu(const QPoint &)));
Run Code Online (Sandbox Code Playgroud)
ShowContextMenuslot应该是类的成员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));
}
Run Code Online (Sandbox Code Playgroud)