-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqchartview_with_zoom_and_drag.h
47 lines (42 loc) · 1.58 KB
/
qchartview_with_zoom_and_drag.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#pragma once
#include <QObject>
#include <QChartView>
//THIS WAS ONLY TESTED ON QLineSeries and default QChart settings
using namespace QtCharts;
class QChartViewWithZoomAndDrag : public QChartView
{
Q_OBJECT
public:
using QChartView::QChartView;
protected:
//ZOOM
void wheelEvent(QWheelEvent *event) override{
//This is imperfect, there is still slight drift when zooming and zoomIn amount != zoomOut amount
//exclude area outside plot
QRectF plotArea = chart()->plotArea();
if(event->position().x()<plotArea.x() || event->position().y()<plotArea.y()
|| event->position().x()>plotArea.x()+plotArea.width() ||event->position().y()>plotArea.y()+plotArea.height())
return;
QPointF mousePos = event->position();
mousePos.setX(mousePos.x()-plotArea.x());
mousePos.setY(mousePos.y()-plotArea.y());
//scroll and zoom
qreal numDegrees = static_cast<qreal>(event->angleDelta().y())/8;
QPointF center = QPointF(plotArea.width()/2,plotArea.height()/2);
chart()->scroll((mousePos.x()-center.x())*(numDegrees/100), -(mousePos.y()-center.y())*(numDegrees/100));
chart()->zoom(1+numDegrees/100);
event->accept();
}
//DRAG
void mouseMoveEvent(QMouseEvent *event) override
{
if(event->buttons().testFlag(Qt::LeftButton))
{
chart()->scroll(-(event->x()-lastMousePos.x()), (event->y()-lastMousePos.y()));
event->accept();
}
lastMousePos = event->pos();
}
private:
QPoint lastMousePos = QPoint(0,0);
};