| 1 |
// Copyright (C) 2016 The Qt Company Ltd. |
| 2 |
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause |
| 3 |
|
| 4 |
#include "graphicsview.h" |
| 5 |
|
| 6 |
#include <QScrollBar> |
| 7 |
#include <QTouchEvent> |
| 8 |
|
| 9 |
GraphicsView::GraphicsView(QGraphicsScene *scene, QWidget *parent) |
| 10 |
: QGraphicsView(scene, parent) |
| 11 |
{ |
| 12 |
viewport()->setAttribute(Qt::WA_AcceptTouchEvents); |
| 13 |
setDragMode(ScrollHandDrag); |
| 14 |
} |
| 15 |
|
| 16 |
bool GraphicsView::viewportEvent(QEvent *event) |
| 17 |
{ |
| 18 |
switch (event->type()) { |
| 19 |
case QEvent::TouchBegin: |
| 20 |
case QEvent::TouchUpdate: |
| 21 |
case QEvent::TouchEnd: |
| 22 |
{ |
| 23 |
QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event); |
| 24 |
const auto touchPoints = touchEvent->points(); |
| 25 |
if (touchPoints.count() == 2) { |
| 26 |
// determine scale factor |
| 27 |
const QEventPoint &touchPoint0 = touchPoints.first(); |
| 28 |
const QEventPoint &touchPoint1 = touchPoints.last(); |
| 29 |
qreal currentScaleFactor = |
| 30 |
QLineF(touchPoint0.position(), touchPoint1.position()).length() |
| 31 |
/ QLineF(touchPoint0.pressPosition(), touchPoint1.pressPosition()).length(); |
| 32 |
if (touchEvent->touchPointStates() & QEventPoint::Released) { |
| 33 |
// if one of the fingers is released, remember the current scale |
| 34 |
// factor so that adding another finger later will continue zooming |
| 35 |
// by adding new scale factor to the existing remembered value. |
| 36 |
totalScaleFactor *= currentScaleFactor; |
| 37 |
currentScaleFactor = 1; |
| 38 |
} |
| 39 |
setTransform(QTransform::fromScale(totalScaleFactor * currentScaleFactor, |
| 40 |
totalScaleFactor * currentScaleFactor)); |
| 41 |
} |
| 42 |
return true; |
| 43 |
} |
| 44 |
default: |
| 45 |
break; |
| 46 |
} |
| 47 |
return QGraphicsView::viewportEvent(event); |
| 48 |
} |