2017-10-18 108 views
1

我目前正在使用Qts Chart绘图工具。我现在有一个情节,我可以通过使用由this示例(小调整)提供的chartview类来放大和缩小。 我希望看到不仅可以缩放的能力,还可以将我的视图按下鼠标中键(这在其他应用程序中使用很多,因此非常直观)。qt图表按住鼠标中键移动视图

我该如何在Qt中做到这一点?如何检查鼠标中键是否被按下并释放,如果鼠标在按下鼠标中键时移动,则更改我的视图...

我确定有人编写过此代码,一个小例子/帮助。

+0

可能重复的:https://stackoverflow.com/questions/18551466/qt-proper-method-to-implement- panningdrag/ –

回答

1

你需要从QChartView派生类和重载鼠标事件:

class ChartView: public QChartView 
{ 
    Q_OBJECT 

public: 
    ChartView(Chart* chart, QWidget *parent = 0); 

protected: 

    virtual void mousePressEvent(QMouseEvent *event) override; 
    virtual void mouseMoveEvent(QMouseEvent *event) override; 

private: 

    QPointF m_lastMousePos; 
}; 

ChartView::ChartView(Chart* chart, QWidget *parent) 
    : QChartView(chart, parent) 
{ 
    setDragMode(QGraphicsView::NoDrag); 
    this->setMouseTracking(true); 
} 

void ChartView::mousePressEvent(QMouseEvent *event) 
{ 
    if (event->button() == Qt::MiddleButton) 
    { 
     QApplication::setOverrideCursor(QCursor(Qt::SizeAllCursor)); 
     m_lastMousePos = event->pos(); 
     event->accept(); 
    } 

    QChartView::mousePressEvent(event); 
} 

void ChartView::mouseMoveEvent(QMouseEvent *event) 
{ 
    // pan the chart with a middle mouse drag 
    if (event->buttons() & Qt::MiddleButton) 
    { 
     QRectF bounds = QRectF(0,0,0,0); 
     for(auto series : this->chart()->series()) 
      bounds.united(series->bounds()) 

     auto dPos = this->chart()->mapToValue(event->pos()) - this->chart()->mapToValue(m_lastMousePos); 

     if (this->rubberBand() == QChartView::RectangleRubberBand) 
      this->chart()->zoom(bounds.translated(-dPos.x(), -dPos.y())); 
     else if (this->rubberBand() == QChartView::HorizontalRubberBand) 
      this->chart()->zoom(bounds.translated(-dPos.x(), 0)); 
     else if (this->rubberBand() == QChartView::VerticalRubberBand) 
      this->chart()->zoom(bounds.translated(0, -dPos.y())); 

     m_lastMousePos = event->pos(); 
     event->accept(); 
    } 

    QChartView::mouseMoveEvent(event); 
} 
+0

什么是m_zoomRect? – user7431005

+0

这是一个更大的项目(https://github.com/nholthaus/chart)的一部分,它也扩展了图表并处理了缩放。我编辑了答案,但在这种情况下,“m_zoomRect”是所有图表系列边界的联合。 –