《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

源码下载

相关推荐
用户8055336980321 小时前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner1 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
BadBadBad__AK1 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境2 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境2 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴3 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境5 天前
C++ 的Eigen 库全解析
c++
卷无止境5 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴5 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
Quz6 天前
QML Hello World 入门示例
qt