2014-06-17 67 views
11

我有一段代碼調用mousePressEvent。我有左鍵單擊輸出光標的座標,我有rightclick做同樣的事情,但我也想要右鍵單擊打開一個上下文菜單。我到目前爲止的代碼是:Qt中的rightclick事件來打開上下文菜單

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++中聲明某些內容。任何建議將不勝感激。

回答

22

customContextMenuRequested在widget的contextMenuPolicy爲Qt::CustomContextMenu時發出,並且用戶已經在widget上請求了上下文菜單。因此,在您的小部件的構造函數中,您可以撥打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)); 
}