欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > Qt自定义按键实现长,短按

Qt自定义按键实现长,短按

2024/10/25 4:24:32 来源:https://blog.csdn.net/propor/article/details/142140130  浏览:    关键词:Qt自定义按键实现长,短按

本文介绍Qt自定义按键实现长,短按。

Qt触摸屏应用有时会涉及到触摸屏按钮长,短按操作,如长按实现关机操作,本文基于普通QPushButton为基类,自定义按键实现长,短按操作。

1.定义新类

这里以QPushButton为基类,自定义一个新类“CustomButton”,参考代码如下:

1)头文件

#ifndef CUSTOMBUTTON_H
#define CUSTOMBUTTON_H#include <QWidget>
#include <QElapsedTimer>
#include <QEvent>
#include <QPushButton>class CustomButton : public QPushButton
{Q_OBJECT
public:explicit CustomButton(QWidget *parent = nullptr);signals:void shortPressed(void);void longPressed(void);public slots:protected:bool event(QEvent *event) override;private:QElapsedTimer pressTime;bool bLongPressed;
};#endif // CUSTOMBUTTON_H

类中声明了2个信号,shortPressed()和longPressed()信号。

2)源文件

若想使能触摸事件,需要在构造函数中设置“setAttribute(Qt::WA_AcceptTouchEvents);”。

#include "custombutton.h"
#include <QMouseEvent>
#include <QDebug>CustomButton::CustomButton(QWidget *parent) : QPushButton(parent)
{setAttribute(Qt::WA_AcceptTouchEvents);bLongPressed = false;
}bool CustomButton::event(QEvent *event)
{if (event->type() == QEvent::TouchBegin) {setPalette(QPalette(Qt::red));pressTime.start();bLongPressed = false;return true;} else if (event->type() == QEvent::TouchUpdate) {if (!bLongPressed && (pressTime.elapsed() >= 3000)) {bLongPressed = true;Q_EMIT longPressed();}return true;} else if (event->type() == QEvent::TouchEnd) {setPalette(QPalette(Qt::white));if (!bLongPressed) {Q_EMIT shortPressed();}return true;} else {}return QPushButton::event(event);
}

注意:在接收到触摸事件后,需要返回“true”,否则后续触摸事件无法接收。

2.控件提升

在界面中放置一个普通的PushButton,右键选择“Promoted Widgets”,添加刚才新建的类。

在界面函数中连接新类中的shortPressed()和longPressed()信号到相应的槽函数,即可实现相应的长,短按功能。

缺陷:长按操作时间不准,有时长按时间较短,有时较长。

总结,本文介绍了Qt自定义按键实现长,短按。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com