Files
hfut-bishe/client/gui/widgets/LongPressSwitchToolButton.cpp
2026-04-08 14:37:01 +08:00

53 lines
1.4 KiB
C++

#include "widgets/LongPressSwitchToolButton.h"
#include <QApplication>
#include <QMouseEvent>
#include <QTimer>
#include <algorithm>
LongPressSwitchToolButton::LongPressSwitchToolButton(QWidget* parent)
: QToolButton(parent) {
m_timer = new QTimer(this);
m_timer->setSingleShot(true);
m_timer->setInterval(m_intervalMs);
connect(m_timer, &QTimer::timeout, this, [this]() {
if (!(QApplication::mouseButtons() & Qt::LeftButton)) {
return;
}
m_longPressEmittedForThisPress = true;
emit longPressTriggered();
});
}
void LongPressSwitchToolButton::setLongPressInterval(int ms) {
m_intervalMs = std::max(50, ms);
if (m_timer) {
m_timer->setInterval(m_intervalMs);
}
}
void LongPressSwitchToolButton::mousePressEvent(QMouseEvent* event) {
if (event->button() == Qt::LeftButton) {
m_longPressEmittedForThisPress = false;
m_timer->start();
}
QToolButton::mousePressEvent(event);
}
void LongPressSwitchToolButton::mouseReleaseEvent(QMouseEvent* event) {
const bool left = (event->button() == Qt::LeftButton);
if (left && m_timer->isActive()) {
m_timer->stop();
}
const bool hadLongPress = left && m_longPressEmittedForThisPress;
QToolButton::mouseReleaseEvent(event);
if (hadLongPress) {
m_longPressEmittedForThisPress = false;
if (isDown()) {
setDown(false);
}
update();
}
}