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

前端之家收集整理的这篇文章主要介绍了c – 在Qt中右键单击事件以打开上下文菜单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一段代码调用一个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"),SLOT(test_slot()));

                menu->exec(w->mapToGlobal(pos));
            }

    }   

}

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

解决方法

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

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

this->setContextMenuPolicy(Qt::CustomContextMenu);

connect(this,SIGNAL(customContextMenuRequested(const QPoint &)),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()),SLOT(removeDataPoint()));
   contextMenu.addAction(&action1);

   contextMenu.exec(mapToGlobal(pos));
}
原文链接:https://www.f2er.com/c/111580.html

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