gpt4 book ai didi

c++ - Qt 中的右键单击事件以打开上下文菜单

转载 作者:IT老高 更新时间:2023-10-28 22:16:34 25 4
gpt4 key购买 nike

我有一段代码调用 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));
}

}

}

我知道我的问题本质上是非常基本的,并且没有正确声明“上下文菜单”。我从许多来源拼凑了这段代码,但不知道如何在 C++ 中声明一些东西。任何建议将不胜感激。

最佳答案

customContextMenuRequested 在小部件的 contextMenuPolicy 为 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));
}

关于c++ - Qt 中的右键单击事件以打开上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24254006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com