《QT实用小工具·五十三》会跑走的按钮

1、概述
源码放在文章末尾

该项目实现了会逃跑的按钮:

两个按钮,一个为普通按钮,另一个为会跑走的按钮

鼠标移到上面时,立刻跑掉

针对鼠标、键盘、触屏进行优化

随机交换两个按钮的文字、偶尔钻到另一个按钮下面、鼠标移开自动重置到原来状态

项目demo演示如下:

项目部分代码如下所示:

cpp 复制代码
#ifndef ESCAPEDIALOG_H
#define ESCAPEDIALOG_H

#include <QObject>
#include <QDialog>
#include <QLabel>
#include <QVBoxLayout>
#include <QDateTime>
#include <random>
#include <QDebug>
#include <QPropertyAnimation>
#include <QTimer>
#include <QKeyEvent>
#include "hoverbutton.h"

class EscapeDialog : public QDialog
{
#define MARGIN 20
    Q_OBJECT
public:
    EscapeDialog(QString title, QString msg, QString esc, QString nor, QWidget* parent = nullptr);

protected:
    void resizeEvent(QResizeEvent *event) override;
    void leaveEvent(QEvent* event) override;

private:
    void resetBtnPos();
    void recoverEscBtnPos();
    void moveEscBtnAni(QPoint aim);
    qint64 getTimestamp();
    int getRandom(int min, int max);
    bool isEqual(int a, int b);

public slots:
    void slotPosEntered(QPoint point);           // 鼠标进入事件:移动按钮或者交换按钮
    void slotEscapeButton(QPoint p = QPoint());  // 移动按钮
    void slotExchangeButton();                   // 交换按钮

private:
    QLabel* msg_lab;
    HoverButton* esc_btn/*accept*/, *nor_btn/*reject*/;

    std::random_device rd;
    std::mt19937 mt;

    bool exchanged; // 两个按钮是否交换了位置
    int escape_count; // 跑动的次数(包括交换)
    int last_escape_index; // 上次交换位置的次数(免得经常性的交换)
    bool has_overlapped; // 是否和另一个按钮进行重叠
};

#endif // ESCAPEDIALOG_H

源码下载

相关推荐
叩码以求索11 分钟前
经典算法实例分析:写字符串需要的行数
开发语言·javascript·ecmascript
我是唐青枫23 分钟前
Kotlin 运算符重载详解:为什么 a += b 有时改对象,有时换对象?
开发语言·kotlin
2zcode27 分钟前
基于MATLAB图像处理的饮料瓶识别与价格显示系统设计与实现
开发语言·图像处理·matlab
王老师青少年编程43 分钟前
2026年6月GESP真题及题解(C++二级):完全平方数计数
c++·题解·真题·gesp·二级·2026年6月·完全平方数计数
zwenqiyu1 小时前
非线性字符串数据结构串讲
数据结构·c++·学习·算法
骑士雄师1 小时前
大模型:临时会话
开发语言·python
尘中远1 小时前
【Qwt 7.0 系列】快速入门与核心新特性概览 —— 更现代的 Qt 数据可视化库
qt·数据可视化·绘图·qwt·科学绘图
努力中的编程者2 小时前
STL-vector的模拟实现
开发语言·c++·算法·stl·vector
薛定猫AI2 小时前
【深度解析】GLM-5.2 与 Z-Code:AI 编程智能体的原理拆解与 Python 调用实战
开发语言·人工智能·python
没文化的阿浩2 小时前
【C++】详解继承机制
开发语言·c++