赞
踩
https://www.bilibili.com/video/BV18B4y1K7Cs?p=7&spm_id_from=pageDriver&vd_source=fa4ef8f26ae084f9b5f70a5f87e9e41b
Qt5跟着视频做即可,Qt6部分代码需要改动,改动的地方注释有写
链接:https://pan.baidu.com/s/158jQbAmv0Y3JipAw-tl9ng
提取码:subw
butterfly.h文件
#ifndef BUTTERFLY_H #define BUTTERFLY_H #include <QWidget> class Butterfly : public QWidget { Q_OBJECT public: explicit Butterfly(QWidget *parent = nullptr); //封装 void fly(); //重载fly,处理方法很多,也可以直接加上默认参数,能实现功能就行 void fly(int min,int max); signals: protected: void paintEvent(QPaintEvent *ev); void timerEvent(QTimerEvent *ev); void mousePressEvent(QMouseEvent* ev); void mouseMoveEvent(QMouseEvent* ev); void enterEvent(QEvent* ev); private: QPixmap m_pixmap; int m_indexPic = 1;//用于描述图片名字 QPoint m_pt; }; #endif // BUTTERFLY_H
butterfly.cpp文件
#include "butterfly.h" #include <QPaintEvent> #include <QPainter> #include <QMouseEvent> #include <QRandomGenerator> #include <QApplication> Butterfly::Butterfly(QWidget *parent) : QWidget{parent} { m_pixmap.load(":/1"); setFixedSize(m_pixmap.size()); //启动定时器 startTimer(100); } void Butterfly::fly() { fly(10,30); } void Butterfly::fly(int min, int max) { m_indexPic++; if (m_indexPic > 2) { m_indexPic = 1; } //构造图片路径 QString name = QString(":/%1").arg(m_indexPic); m_pixmap.load(name); update(); //蝴蝶移动的步长10 -29的随机数 int stepX = QRandomGenerator::global()->bounded(min,max); int stepY = QRandomGenerator::global()->bounded(min,max); int curX = this->geometry().topLeft().x() + stepX; int curY = this->geometry().topLeft().y() + stepY; //Qt6没有视频中的方法,要换成这样写 QRect screenRect=QGuiApplication::primaryScreen()->geometry(); if (curX >= screenRect.right()) { curX = screenRect.left(); } if (curY >= screenRect.bottom()) { curY = screenRect.top(); } move(curX,curY); } void Butterfly::paintEvent(QPaintEvent *ev) { QPainter painter(this); painter.drawPixmap(rect(),m_pixmap); } void Butterfly::timerEvent(QTimerEvent *ev) { fly(); } void Butterfly::mousePressEvent(QMouseEvent *ev) { if (ev->button() == Qt::LeftButton) { m_pt = ev->globalPos() - this->geometry().topLeft(); } } void Butterfly::mouseMoveEvent(QMouseEvent *ev) { /*ev>buttons 返回值是一些二进制值,每个二进制值对应鼠标的一个键位, * 如果两个二进制按位与返回1,则是同一个键位,否则不是 */ if (ev->buttons() & Qt::LeftButton) { this->move(ev->globalPos() - m_pt); } } void Butterfly::enterEvent(QEvent *ev) { fly(-200,200); }
QMouseEvent::buttons返回值是各种二进制数,每个二进制数对应的就是一个鼠标键位。如果两个二进制按位与返回1,则是同一个键位,否则不是
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。