码迷,mamicode.com
首页 > 其他好文 > 详细

QGraphicsView实现飞舞的蝴蝶

时间:2017-07-14 14:52:47      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:.com   tom   event   timer   ati   bsp   art   deb   article   

class Butterfly : public QObject,public QGraphicsItem
{
    Q_OBJECT

public:
    Butterfly();
    ~Butterfly();
    void timerEvent(QTimerEvent *);
    QRectF boundingRect() const;
protected:
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */);

private:
    bool up;
    QPixmap pixUp;
    QPixmap pixDown;
    qreal angle;
    
};
static const double PI = 3.14159265358979323846264338327950288419717;
Butterfly::Butterfly()
{
    setFlag(QGraphicsItem::ItemIsMovable);
    pixUp.load("Resources/butterfly1.png");
    pixDown.load("Resources/butterfly2.png");
    up = true;
    angle = 0;
    startTimer(100);
}
Butterfly::~Butterfly()
{
}
QRectF Butterfly::boundingRect() const
{
    qreal adjust = 8;
    return QRectF(-pixUp.width() / 2 - adjust, -pixUp.height() / 2 - adjust, pixUp.width() + adjust * 2, pixUp.height() + adjust * 2);
}
void Butterfly::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    if (up)
    {
        painter->drawPixmap(boundingRect().topLeft(), pixUp);
        up = !up;
    }
    else
    {
        painter->drawPixmap(boundingRect().topLeft(), pixDown);
        up = !up;
    }
}
void Butterfly::timerEvent(QTimerEvent *)
{
    qreal edgex = scene()->sceneRect().right() + boundingRect().width() / 2;
    qreal edgetop = scene()->sceneRect().top() + boundingRect().height() / 2;
    qreal edgebottom = scene()->sceneRect().bottom() + boundingRect().height() / 2;
    qreal eageLeft = scene()->sceneRect().left()-boundingRect().width();
    //qDebug() << scene()->itemsBoundingRect();
    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());
    if (pos().x() < eageLeft)
        setPos(scene()->sceneRect().right(), pos().y());
    angle += (qrand() % 10) / 20.0;//angle+=0~0.5
    qreal dx = fabs(sin(angle*PI)*10.0);//x轴方向0~10
    qreal dy = (qrand() % 20) - 10.0;//y轴方向-10~10
    setPos(mapToParent(-dx, dy));
    update();
}
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene scene;
    scene.setSceneRect(-300, -300, 600, 600);
    Butterfly *item = new Butterfly;
    item->setPos(-100, 0);
    scene.addItem(item);
    QGraphicsView view(&scene);
    view.resize(800, 600);
    view.show();
    return a.exec();
}

技术分享

技术分享

技术分享

 

转自http://blog.csdn.net/taiyang1987912/article/details/38681969

QGraphicsView实现飞舞的蝴蝶

标签:.com   tom   event   timer   ati   bsp   art   deb   article   

原文地址:http://www.cnblogs.com/loki1412/p/7169901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!