用Qt实现一群飞舞的蝴蝶,看起来还是蛮漂亮的,下面来给出代码吧,难度不大,也没有什么好分析的,就简单的写了点注释,在我的资源空间也上传了代码,需要的可以去下载。如果运行过程中有什么疑问的话可以留言于本人联系。
//***************mainwindow.h*******************//
#ifndef BUTTERFLY_H
#define BUTTERFLY_H
#include <QGraphicsItem>
#include <QObject>
class Butterfly : public QObject, public QGraphicsItem
{
Q_OBJECT
public:
Butterfly();
void timerEvent(QTimerEvent *);//声明定时器的timerEvent()函数
QRectF boundingRect() const; //该函数必须实现
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
//重画函数
private:
bool up; //用于实现蝴蝶的飞舞画面
QPixmap pix_up; //蝴蝶图案一
QPixmap pix_down; //蝴蝶
qreal angle;
};
#endif // BUTTERFLY_H
//***************end end end end*******************//
//***************mainwindow.cpp*******************//
#include "butterfly.h"#include <QtGui>#include <math.h>static const double PI = 3.14;Butterfly::Butterfly(){pix_up.load(":/images/butterfly1.png"); //图片的加载pix_down.load(":/images/butterfly2.png");up = true;startTimer(100); //时间间隔100毫秒
}
QRectF
Butterfly::boundingRect() const //加载蝴蝶项目的限定范围,以其自身的坐标系为基础设定的{
qreal adjust = 2;return QRectF(-pix_up.width()/2-adjust,-pix_up.height()/2-adjust,pix_up.width()+adjust*2,pix_up.height()+2*adjust);}
//一下函数实现蝴蝶的飞舞效果
void
Butterfly::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
if(up){painter->drawPixmap(boundingRect().topLeft(),pix_up);//绘图up = !up;}else{painter->drawPixmap(boundingRect().topLeft(),pix_down);up = !up;}}
//判断蝴蝶的运动范围,并做相应的处理相信根据函数名大家都知道啥意思
void
Butterfly::timerEvent(QTimerEvent *){
// edge controllqreal edgex = scene()->sceneRect().right()+boundingRect().width()/2;qreal edgetop = scene()->sceneRect().top()+boundingRect().height()/2;qreal edgebottom = scene()->sceneRect().bottom()+boundingRect().height()/2;
if (pos().x() >= edgex)setPos(scene()->sceneRect().left(),pos().y());if (pos().y() <= edgetop)setPos(pos().x(),scene()->sceneRect().bottom());if (pos().y() >= edgebottom)setPos(pos().x(),scene()->sceneRect().top());
angle += (qrand()%10)/20.0;qreal dx = fabs(sin(angle*PI)*10.0);qreal dy = (qrand()%20)-10.0;//flash = !flash;setPos(mapToParent(dx,dy));//映射到场景的坐标update();}
//***************end end end end*******************//
//***************main.cpp*******************//
#include <QApplication>#include <QGraphicsScene>#include <QGraphicsView>#include "butterfly.h"int main(int argc, char * argv[]){
QApplication app(argc,argv);QGraphicsScene *scene = new QGraphicsScene;scene->setSceneRect(QRectF(-400,-300,800,600));for(int i=0;i<100;i++){Butterfly *butterfly = new Butterfly;//为每一个飞舞的湖底产生一个随机位置butterfly->setPos((qrand()%int(scene->sceneRect().width()))-400,(qrand()%int(scene->sceneRect().height()))-300);scene->addItem(butterfly);}
QGraphicsView *view = new QGraphicsView;view->setScene(scene);view->setMaximumSize(800,600);view->setMinimumSize(800,600);view->show();return app.exec();}
//***************main.cpp*******************//
以上便是实现飞舞的蝴蝶群全部的实现代码了 欢迎共同学习交流所用