1 #include "fly.h"
2
3 fly::fly(QObject *parent) : QObject(parent)
4 {
5 //载入
6 up = true;
7 pix_up.load("up.png");
8 pix_down.load("down.png");
9
10 startTimer(30);
11 }
12
13 //图元的边界区域
14 QRectF fly::boundingRect() const
15 {
16 qreal angletemp = 2;
17 return QRectF(-pix_up.width()/2-angletemp,
18 -pix_up.height()/2-angletemp,
19 pix_up.width()+angletemp*2,
20 pix_up.height()+angletemp*2);
21 }
22
23 //定时器函数
24 void fly::timerEvent(QTimerEvent *event)
25 {
26 //边界控制
27 qreal edgex = scene()->sceneRect().right()+boundingRect().width()/2;
28 qreal edgetop=scene()->sceneRect().top()+boundingRect().height()/2;
29 qreal edgebottom = scene()->sceneRect().bottom()+boundingRect().height()/2;
30
31 if(pos().x()>=edgex)
32 setPos(scene()->sceneRect().left(),pos().y());
33 if(pos().y()<=edgetop)
34 setPos(pos().x(),scene()->sceneRect().bottom());
35 if(pos().y()>=edgebottom)
36 setPos(pos().x(),scene()->sceneRect().top());
37
38 #define PI 3.14
39 angle += (qrand() % 10)/20.0;
40 qreal dx = fabs(sin(angle*PI)*10);
41 qreal dy = (qrand()%20)-10.0;
42
43 //设置位置,转换坐标
44 setPos(mapToParent(dx,dy));
45 }
46
47 void fly::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
48 {
49 if(up)
50 {
51 painter->drawPixmap(boundingRect().topLeft(),pix_up);
52 up = !up;
53 }
54 else
55 {
56 painter->drawPixmap(boundingRect().topLeft(),pix_down);
57 up = !up;
58 }
59 }