Game Programming using Qt 5 Beginner's Guide
上QQ阅读APP看书,第一时间看更新

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.