#include "slideview.hpp" #include #include #include const double speed_slow_unit = 0.25; SlideView::SlideView(QWidget * parent) : QWidget(parent), is_pressed_(false), msec_time_(0), speed_(0.0), move_direction_(Stable) { slide_timer_.setInterval(150); connect(&slide_timer_, &QTimer::timeout, this, [=]() { if (is_pressed_) { if (cur_x_ != this->pos().x()) { double offset = this->pos().x() - cur_x_; speed_ = offset / slide_timer_.interval(); } else { speed_ = 0.0; } cur_x_ = this->pos().x(); } }); speed_timer_.setInterval(20); speed_timer_.setSingleShot(false); connect(&speed_timer_, &QTimer::timeout, this, [=]() { int offset = speed_ * 10; int now_x = this->pos().x(); int now_y = this->pos().y(); if (now_x + offset < 0) { now_x = 0; speed_timer_.stop(); return; } if (now_x + offset + width() > 1400) { now_x = 1400 - width(); speed_timer_.stop(); return; } now_x += offset; move(now_x, now_y); if (speed_ > speed_slow_unit) { speed_ -= speed_slow_unit; } else if (speed_ < -speed_slow_unit) { speed_ += speed_slow_unit; } else { speed_ = 0.0; speed_timer_.stop(); } }); } SlideView::~SlideView() { } void SlideView::paintEvent(QPaintEvent*) { QPainter painter(this); painter.fillRect(0, 0, width(), height(), QColor(Qt::red)); } void SlideView::mousePressEvent(QMouseEvent* ptr_event) { speed_timer_.stop(); cur_x_ = pos().x(); msec_time_ = QDateTime::currentDateTime().toMSecsSinceEpoch(); is_pressed_ = true; speed_ = 0.0; } void SlideView::mouseMoveEvent(QMouseEvent* ptr_event) { if (is_pressed_) { move(pos().x() + ptr_event->x(), pos().y()); MoveDirection direction = ptr_event->x() > 0 ? MoveRight : MoveLeft; if (direction != move_direction_) { move_direction_ = direction; speed_ = 0.0; msec_time_ = QDateTime::currentDateTime().toMSecsSinceEpoch(); } if (!slide_timer_.isActive()) slide_timer_.start(); } } void SlideView::mouseReleaseEvent(QMouseEvent* ptr_event) { if (is_pressed_) { if (speed_ >= 0.000001 || speed_ <= -0.000001) { speed_timer_.start(); } else { time_t inteval = QDateTime::currentDateTime().toMSecsSinceEpoch() - msec_time_; if (inteval <= 200 && cur_x_ != this->pos().x()) { double offset = this->pos().x() - cur_x_; speed_ = offset / inteval; speed_timer_.start(); } } move_direction_ = Stable; pre_x_ = 0; cur_x_ = 0; is_pressed_ = false; msec_time_ = 0; } slide_timer_.stop(); }