Time for action – Implementing the ability to scale the scene

Let's allow the user to scale the scene using the mouse wheel on the view. Switch to the view.h file and add a declaration and an implementation of the wheelEvent() virtual function using the same method we just used in the SineItem class. Write the following code in the view.cpp file:

void View::wheelEvent(QWheelEvent *event)
{
    QGraphicsView::wheelEvent(event);
    if (event->isAccepted()) {
        return;
    }
    const qreal factor = 1.1;
    if (event->angleDelta().y() > 0) {
        scale(factor, factor);
    } else {
        scale(1 / factor, 1 / factor);
    }
    event->accept();
}

If you run the application now, you can scale the sine graph using the mouse wheel.

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.