Qt 自定义按钮 区分点按与长按信号 适配触摸事件
效果
使用示例
// 点按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
#pragma once#include <QToolButton>class JogButton : public QToolButton
{Q_OBJECTpublic: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
#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();
}