Zoom Line Example▲
The example shows how to create your own custom zooming effect with QRubberBand by using a mouse and how to use touch gestures for paning and zooming.
Running the Example▲
To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.
Customizing Zooming Effects▲
Let's first create a line series with some example data.
QLineSeries *
series =
new
QLineSeries();
for
(int
i =
0
; i &
lt; 500
; i++
) {
QPointF p((qreal) i, qSin(M_PI /
50
*
i) *
100
);
p.ry() +=
QRandomGenerator::
global()-&
gt;bounded(20
);
*
series &
lt;&
lt; p;
}
Then we create a custom chart view by deriving from QChartView:
class
ChartView : public
QChartView
We override mouse and key event handling
protected
:
bool
viewportEvent(QEvent *
event);
void
mousePressEvent(QMouseEvent *
event);
void
mouseMoveEvent(QMouseEvent *
event);
void
mouseReleaseEvent(QMouseEvent *
event);
void
keyPressEvent(QKeyEvent *
event);
Then we implement a custom logic for mouse and key events. For example pressing the '+' key will zoom in and pressing the '-' key will zoom out.
void
ChartView::
keyPressEvent(QKeyEvent *
event)
{
switch
(event-&
gt;key()) {
case
Qt::
Key_Plus:
chart()-&
gt;zoomIn();
break
;
case
Qt::
Key_Minus:
chart()-&
gt;zoomOut();
break
;
We also create our own QChart:
class
Chart : public
QChart
Where we can handle the gestures:
bool
Chart::
sceneEvent(QEvent *
event)
{
if
(event-&
gt;type() ==
QEvent::
Gesture)
return
gestureEvent(static_cast
&
lt;QGestureEvent *&
gt;(event));
return
QChart::
event(event);
}
bool
Chart::
gestureEvent(QGestureEvent *
event)
{
if
(QGesture *
gesture =
event-&
gt;gesture(Qt::
PanGesture)) {
QPanGesture *
pan =
static_cast
&
lt;QPanGesture *&
gt;(gesture);
QChart::
scroll(-
(pan-&
gt;delta().x()), pan-&
gt;delta().y());
}
if
(QGesture *
gesture =
event-&
gt;gesture(Qt::
PinchGesture)) {
QPinchGesture *
pinch =
static_cast
&
lt;QPinchGesture *&
gt;(gesture);
if
(pinch-&
gt;changeFlags() &
amp; QPinchGesture::
ScaleFactorChanged)
QChart::
zoom(pinch-&
gt;scaleFactor());
}
return
true
;
}
Note that you will need to call grabGesture() to both QMainWindow and QChart.