rightclick event in Qt to open a context menu

ahle6481 picture ahle6481 · Jun 17, 2014 · Viewed 43.3k times · Source

I have a segment of code that calls a mousePressEvent. I have the left-click output the coordinates of the cursor, and I have rightclick do the same, but I also want to have the rightclick open a context menu. The code I have so far is:

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

    }   

}

I know that my problem is very fundamental in nature, and that 'contextmenu' is not properly declared. I have pieced together this code from many sources, and do not know how to declare something in c++. Any advice would be greatly appreciated.

Answer

Nejat picture Nejat · Jun 17, 2014

customContextMenuRequested is emitted when the widget's contextMenuPolicy is Qt::CustomContextMenu, and the user has requested a context menu on the widget. So in the constructor of your widget you can call setContextMenuPolicy and connect customContextMenuRequested to a slot to make a custom context menu.

In the constructor of plotspace :

this->setContextMenuPolicy(Qt::CustomContextMenu);

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

ShowContextMenu slot should be a class member of plotspace like :

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