Zoom Line Example

The example shows how to create your own custom zooming effect.

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.

../_images/examples_zoomlinechart1.png ../_images/examples_zoomlinechart2.png

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.

series = QLineSeries()
for i in range(0, 500):
    p = QPointF((qreal) i, qSin(M_PI / 50 * i) * 100)
    p.ry() += QRandomGenerator.global().bounded(20)
    series << p

Then we create a custom chart view by deriving from QChartView :

class ChartView(QChartView):

We override mouse and key event handling

    viewportEvent = bool(QEvent event)
    def mousePressEvent(event):
    def mouseMoveEvent(event):
    def mouseReleaseEvent(event):
    def keyPressEvent(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.

def keyPressEvent(self, event):

    switch (event.key()) {
    Qt.Key_Plus: = case()
    Qt.Key_Minus: = case()

We also create our own QChart :

class Chart(QChart):

Where we can handle the gestures:

def sceneEvent(self, QEvent event):

    if (event.type() == QEvent.Gesture)
        def gestureEvent((event)):
    return QChart.event(event)

def gestureEvent(self, QGestureEvent event):

    if (QGesture gesture = event.gesture(Qt.PanGesture)) {
        pan = QPanGesture (gesture)
        QChart.scroll(-(pan.delta().x()), pan.delta().y())

    if (QGesture gesture = event.gesture(Qt.PinchGesture)) {
        pinch = QPinchGesture (gesture)
        if (pinch.changeFlags()  QPinchGesture.ScaleFactorChanged)

    return True

Note that you will need to call grabGesture() to both QMainWindow and QChart .

Example project @ code.qt.io