在Qt中管理右键和左键

managing right and left clicks in Qt

本文关键字:右键 管理 Qt      更新时间:2023-10-16

我有一个复杂的Qt GUI,其中GUI的一部分显示具有各种数据点的绘图。

当前在绘图上左击或右击时,它返回单击位置的x-y值。我的工作是更新这一点,使左键点击仍然做同样的事情,但右键选择最近的数据点,并打开一个上下文菜单,允许我删除所述数据点。这个想法是手动能够去除异常值。

更新:我认为我已经找到了目前负责返回x-y值的代码段:

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

就像我说的,我需要把它变成左击执行相同的操作,右击打开一个上下文菜单。如有任何建议,不胜感激。

您必须检查使用了哪个鼠标按钮。一般来说,我更喜欢处理mouseReleaseEvent而不是mousePressEvent,因为它可以更好地复制传统的鼠标行为。但这两件事都行得通。一个例子:

void mouseReleaseEvent(QMouseEvent *e)
{
  if (e->button() == Qt::LeftButton)    // Left button...
  {
    // Do something related to the left button
  }
  else if (e->button() == Qt::RightButton)   // Right button...
  {
    // Do something related to the right button
  }
}

如果你愿意,你也可以处理Qt::MidButton