1. 程式人生 > >QGraphicsView實現飛舞的蝴蝶

QGraphicsView實現飛舞的蝴蝶

pos alt bug csdn sources lag rect() logs 3.1

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實現飛舞的蝴蝶