Qt 自定义按钮 区分点按与长按信号 适配触摸事件
效果
使用示例
cpp
// 点按
connect(ui.btnLeft, &JogButton::stepclicked, this, &MainWindow::btnLeft_clicked);
// 长按开始
connect(ui.btnLeft, &JogButton::continueOn, this, &MainWindow::slotJogLeftOn);
// 长按结束
connect(ui.btnLeft, &JogButton::continueOff, this, &MainWindow::slotJogLeftOff);
源码
JogButton.h
cpp
#pragma once
#include <QToolButton>
class JogButton : public QToolButton
{
Q_OBJECT
public:
JogButton(QWidget *parent = nullptr);
JogButton(const QString& title, QWidget *parent = nullptr);
~JogButton();
protected:
virtual bool event(QEvent *e) override;
signals:
void stepclicked(); // 点动
void continueOn(); // 持续驱动开启
void continueOff(); // 持续驱动关闭
private:
void pressfunc();
void releasefunc();
private:
bool iscontinue = false;
bool ispress = false;
};
JogButton.cpp
cpp
#include "JogButton.h"
#include <QTimer>
#include <QTouchEvent>
#include <QDebug>
#define PRESS_TIME 200 // 触发长按时间
JogButton::JogButton(QWidget *parent)
: QToolButton(parent)
{
setAttribute(Qt::WA_AcceptTouchEvents);//支持多点触控
}
JogButton::JogButton(const QString& title, QWidget *parent)
: QToolButton(parent)
{
setAttribute(Qt::WA_AcceptTouchEvents);//支持多点触控
setText(title);
}
JogButton::~JogButton()
{
}
bool JogButton::event(QEvent * e)
{
if (this->isEnabled()) {
switch (e->type()) {
case QEvent::TouchBegin:
case QEvent::MouseButtonPress:
pressfunc();
break;
case QEvent::TouchEnd:
case QEvent::MouseButtonRelease:
releasefunc();
break;
}
}
return QToolButton::event(e);
}
void JogButton::pressfunc()
{
if (ispress) return;
ispress = true;
iscontinue = false;
QTimer::singleShot(PRESS_TIME, [=] {
iscontinue = true;
if (ispress) emit continueOn();
});
}
void JogButton::releasefunc()
{
if (!ispress) return;
ispress = false;
if (iscontinue) emit continueOff();
else emit stepclicked();
}