BibleTime
cscrollbutton.cpp
Go to the documentation of this file.
1 /*********
2 *
3 * In the name of the Father, and of the Son, and of the Holy Spirit.
4 *
5 * This file is part of BibleTime's source code, https://bibletime.info/
6 *
7 * Copyright 1999-2021 by the BibleTime developers.
8 * The BibleTime source code is licensed under the GNU General Public License
9 * version 2.0.
10 *
11 **********/
12 
13 #include "cscrollbutton.h"
14 
15 #include <cmath>
16 #include <QCursor>
17 #include <QMouseEvent>
18 #include <QPoint>
19 #include <Qt>
20 
21 
23  : QToolButton(parent), m_isLocked(false), m_movement(0.0) {
24  setFocusPolicy(Qt::WheelFocus);
25  setCursor(Qt::SplitVCursor);
26 }
27 
28 void CScrollButton::mousePressEvent(QMouseEvent *e) {
29  if (m_isLocked) return;
30  if (e->button() != Qt::LeftButton) return;
31  m_isLocked = true;
32  grabMouse(Qt::BlankCursor);
33  Q_EMIT lock();
34 }
35 
36 void CScrollButton::mouseReleaseEvent(QMouseEvent *e) {
37  if (!m_isLocked) return;
38  if (e->button() != Qt::LeftButton) return;
39  m_isLocked = false;
40  m_movement = 0.0;
41  releaseMouse();
42  Q_EMIT unlock();
43 }
44 
45 void CScrollButton::mouseMoveEvent(QMouseEvent *e) {
46  if (m_isLocked) {
47  // Recalculate the center of the widget (might change during grab):
48  QPoint center(mapToGlobal(QPoint(width() / 2, height() / 2)));
49 
50  // Calculate movement change:
51  #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
52  int vchange = (e->globalY() - center.y());
53  #else
54  int vchange = (e->globalPosition().toPoint().y() - center.y());
55  #endif
56 
57  if (vchange != 0) {
58  // Adapt the change value, so we get a more natural feeling:
59  if(vchange > 0)
60  m_movement += pow(vchange/10.0f, 1.2);
61  else // (vchange < 0)
62  m_movement -= pow(-vchange/10.0f, 1.2);
63 
64  // Emit the change request signal only when the mouse was moved far enough
65  if (m_movement >= 1.0 || m_movement <= -1.0) {
66  Q_EMIT change_requested(static_cast<int>(m_movement));
67  m_movement = 0.0;
68  }
69  }
70 
71  // Move the mouse cursor to the center of this widget:
72  QCursor::setPos(center);
73  }
74  else {
75  QToolButton::mouseMoveEvent(e);
76  }
77 }
void mouseReleaseEvent(QMouseEvent *e) override
If the mouse is grabbed and we release the left mouse button, releases the mouse and emits unlock().
void unlock()
The unlock() signal is emitted when the button releases the leaves the locked state.
float m_movement
The amount the mouse moved.
Definition: cscrollbutton.h:84
void lock()
The lock() signal is emitted when the button grabs the mouse and enters the locked state.
CScrollButton(QWidget *parent=nullptr)
bool m_isLocked
Indicates whether the button is in locked state or not.
Definition: cscrollbutton.h:76
void mousePressEvent(QMouseEvent *e) override
Grabs the mouse on left button click and emits lock().
void mouseMoveEvent(QMouseEvent *e) override
void change_requested(int count)
Indicates a change the user made by moving the mouse.