C++ 右键单击Qt中的事件以打开关联菜单
我有一段代码调用mousePressEvent。我用鼠标左键单击输出光标的坐标,用鼠标右键单击也可以,但我也想用鼠标右键单击打开上下文菜单。到目前为止,我掌握的代码是:C++ 右键单击Qt中的事件以打开关联菜单,c++,qt,events,contextmenu,C++,Qt,Events,Contextmenu,我有一段代码调用mousePressEvent。我用鼠标左键单击输出光标的坐标,用鼠标右键单击也可以,但我也想用鼠标右键单击打开上下文菜单。到目前为止,我掌握的代码是: void plotspace::mousePressEvent(QMouseEvent*event) { double trange = _timeonright - _timeonleft; int twidth = width(); double tinterval = trange/twidth;
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));
}
}
}
void plotspace::mousePressEvent(QMouseEvent*event)
{
双重交易=_timeonright-_timeonleft;
int twidth=宽度();
双t=交易量/分次;
int xclicked=event->x();
_xvaluecoordinate=\u timeonleft+tinterval*xclicked;
double fmax=Data.plane(X,0.max();
double fmin=Data.plane(X,0.min();
双fmargin=(fmax-fmin)/40;
int fheight=高度();
双finterval=((fmax-fmin)+4*fmargin)/fheight;
int yclicked=event->y();
_yvaluecoordinate=(fmax+fmargin)-finterval*yclicked;
当小部件的contextMenuPolicy为Qt::customContextMenuRequested
且用户已请求小部件上的上下文菜单时,将发出customContextMenuRequested
,因此在小部件的构造函数中,您可以调用setContextMenuPolicy
并将customContextMenuRequested
连接到插槽以创建cus汤姆上下文菜单
在绘图空间的构造函数中
:
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));
}