《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

源码下载

相关推荐
感哥9 小时前
C++ 面向对象
c++
沐怡旸11 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
感哥17 小时前
C++ STL 常用算法
c++
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
博笙困了2 天前
AcWing学习——双指针算法
c++·算法
感哥2 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++