事件经过:事件派发(QApplication调用notify())->事件过滤(eventFilter())->事件分发(窗口事件分发器event())->事件处理(事件处理器函数,鼠标事件,键盘事件,绘图事件)
以上函数由qt控件维护,会在合适的时机执行,是虚函数可以重写。
两张蝴蝶图片实现飞舞效果
//.h文件
#ifndef BUTTERFLY_H
#define BUTTERFLY_H
#include <QPaintEvent>
#include <QWidget>
class Butterfly : public QWidget
{
Q_OBJECT
public:
explicit Butterfly(QWidget *parent = nullptr);
void fly(int min, int max);
private:
QPixmap m_pixmap;
int m_index = 1;
QPoint m_pt;
protected:
void paintEvent(QPaintEvent *ev);
void timerEvent(QTimerEvent *ev);
void mousePressEvent(QMouseEvent *ev);
void mouseMoveEvent(QMouseEvent *ev);
void enterEvent(QEvent *ev);
signals:
};
#endif // BUTTERFLY_H
//cpp文件
#include "butterfly.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QPainter>
#include <QRandomGenerator>
Butterfly::Butterfly(QWidget *parent)
: QWidget{parent}
{
m_pixmap.load(":/1");
setFixedSize(m_pixmap.size());
startTimer(100);
}
void Butterfly::fly(int min,int max)
{
m_index++;
if(m_index>2)
{
m_index = 1;
}
QString name = QString(":/%1").arg(m_index);
m_pixmap.load(name);
update();
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;
QDesktopWidget *desk = QApplication::desktop();
if(curX <= desk->screenGeometry().left())
{
curX = desk->screenGeometry().right();
}
if(curY >= desk->screenGeometry().bottom())
{
curY = desk->screenGeometry().top();
}
move(curX,curY);
}
void Butterfly::paintEvent(QPaintEvent *ev)
{
QPainter p(this);
p.drawPixmap(rect(),m_pixmap);
}
void Butterfly::timerEvent(QTimerEvent *ev)
{
fly(100,300);
}
void Butterfly::mousePressEvent(QMouseEvent *ev)
{
if(ev->button() == Qt::LeftButton)
{
m_pt = ev->globalPos()-this->geometry().topLeft();
}
}
void Butterfly::mouseMoveEvent(QMouseEvent *ev)
{
if(ev->buttons()&Qt::LeftButton)
{
this->move(ev->globalPos()-m_pt);
}
}
void Butterfly::enterEvent(QEvent *ev)
{
fly(-600,600);
}
//主窗口
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "butterfly.h"
#include <QRandomGenerator>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//去边框
setWindowFlags(windowFlags()|Qt::FramelessWindowHint);
//设置窗口透明
setAttribute(Qt::WA_TintedBackground);
//最大化
showMaximized();
for (int var = 0; var < 100; ++var) {
Butterfly *win = new Butterfly(this);
win->move(QRandomGenerator::global()->bounded(this->width()),
QRandomGenerator::global()->bounded(this->height()));
win->show();
}
}
MainWindow::~MainWindow()
{
delete ui;
}
标签:Butterfly,include,qt,int,void,学习,事件,ev,MainWindow
From: https://blog.csdn.net/qq_45080494/article/details/144442403