// Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause #include "graphicsview.h" #include #include GraphicsView::GraphicsView(QGraphicsScene *scene, QWidget *parent) : QGraphicsView(scene, parent) { viewport()->setAttribute(Qt::WA_AcceptTouchEvents); setDragMode(ScrollHandDrag); } bool GraphicsView::viewportEvent(QEvent *event) { switch (event->type()) { case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: { QTouchEvent *touchEvent = static_cast(event); const auto touchPoints = touchEvent->points(); if (touchPoints.count() == 2) { // determine scale factor const QEventPoint &touchPoint0 = touchPoints.first(); const QEventPoint &touchPoint1 = touchPoints.last(); qreal currentScaleFactor = QLineF(touchPoint0.position(), touchPoint1.position()).length() / QLineF(touchPoint0.pressPosition(), touchPoint1.pressPosition()).length(); if (touchEvent->touchPointStates() & QEventPoint::Released) { // if one of the fingers is released, remember the current scale // factor so that adding another finger later will continue zooming // by adding new scale factor to the existing remembered value. totalScaleFactor *= currentScaleFactor; currentScaleFactor = 1; } setTransform(QTransform::fromScale(totalScaleFactor * currentScaleFactor, totalScaleFactor * currentScaleFactor)); } return true; } default: break; } return QGraphicsView::viewportEvent(event); }