Qt中的右键单击事件用于打开上下文菜单。

38

我有一段调用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++中声明。任何建议都将不胜感激。

1个回答

77

customContextMenuRequested 在小部件的 contextMenuPolicy 为 Qt::CustomContextMenu 时发出,当用户在小部件上请求上下文菜单时也会发出该信号。因此,在您的小部件构造函数中,您可以调用 setContextMenuPolicy 并将 customContextMenuRequested 连接到一个槽,以创建一个自定义上下文菜单。

plotspace 的构造函数中:

this->setContextMenuPolicy(Qt::CustomContextMenu);

connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), 
        this, SLOT(ShowContextMenu(const QPoint &)));

ShowContextMenu插槽应该是plotspace类的成员,就像这样:

ShowContextMenu slot should be a class member of plotspace like :

返回:

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));
}

据我所知,本地定义变量的生命周期仅限于它们被定义的域。例如,在这里,contextMenu和action1是局部变量,当函数ShowContextMenu结束时,它们就会被删除。那么为什么上面的代码仍然有效呢?难道我们不应该将这些变量定义为相应类的成员变量吗? - alireza
2
@alireza exec 函数在 QMenu 中同步执行菜单。 即该函数不会到达其末尾,而是在 exec 处等待,直到菜单关闭。 - Nejat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接