summaryrefslogtreecommitdiffstats
path: root/examples/gestures/imageviewer/tapandholdgesture.cpp
blob: c6f6779fe078aebc79bc13ab12b2024ff487eba8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include "tapandholdgesture.h"

#include <QtGui/qevent.h>

/*!
    \class TapAndHoldGesture
    \since 4.6

    \brief The TapAndHoldGesture class represents a Tap-and-Hold gesture,
    providing additional information.
*/

const int TapAndHoldGesture::iterationCount = 40;
const int TapAndHoldGesture::iterationTimeout = 50;

/*!
    Creates a new Tap and Hold gesture handler object and marks it as a child
    of \a parent.

    On some platforms like Windows there is a system-wide tap and hold gesture
    that cannot be overriden, hence the gesture might never trigger and default
    context menu will be shown instead.
*/
TapAndHoldGesture::TapAndHoldGesture(QWidget *parent)
    : QGesture(parent), iteration(0)
{
}

/*! \internal */
bool TapAndHoldGesture::filterEvent(QEvent *event)
{
    if (!event->spontaneous())
        return false;
    const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
    switch (event->type()) {
    case QEvent::TouchBegin: {
        if (timer.isActive())
            timer.stop();
        timer.start(TapAndHoldGesture::iterationTimeout, this);
        const QPoint p = ev->touchPoints().at(0).pos().toPoint();
        position = p;
        break;
    }
    case QEvent::TouchUpdate:
        if (ev->touchPoints().size() == 1) {
            const QPoint startPos = ev->touchPoints().at(0).startPos().toPoint();
            const QPoint pos = ev->touchPoints().at(0).pos().toPoint();
            if ((startPos - pos).manhattanLength() > 15)
                reset();
        } else {
            reset();
        }
        break;
    case QEvent::TouchEnd:
        reset();
        break;
    default:
        break;
    }
    return false;
}

/*! \internal */
void TapAndHoldGesture::timerEvent(QTimerEvent *event)
{
    if (event->timerId() != timer.timerId())
        return;
    if (iteration == TapAndHoldGesture::iterationCount) {
        timer.stop();
        setState(Qt::GestureFinished);
        emit triggered();
    } else {
        setState(Qt::GestureStarted);
        emit triggered();
    }
    ++iteration;
}

/*! \internal */
void TapAndHoldGesture::reset()
{
    if (state() != Qt::NoGesture)
        emit cancelled();
    setState(Qt::NoGesture);
    timer.stop();
    iteration = 0;
}

/*!
    \property TapAndHoldGesture::pos

    \brief The position of the gesture.
*/
QPoint TapAndHoldGesture::pos() const
{
    return position;
}