参考:Qt4 开发实践第八章 图形视图QGraphicsView

#ifndef DRIVEDGRAPH_H
#define DRIVEDGRAPH_H #include <QObject>
#include <QGraphicsItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPainter> class DrivedGraph : public QObject,public QGraphicsItem
{
Q_OBJECT
public:
DrivedGraph();
void timerEvent(QTimerEvent *); // 在定时器里对QGraphicsItem 进行重画
QRectF boundingRect() const; // 为图元限定区域范围,所有继承自QGraphicsItem的自定义图元都必须实现此函数
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); // 重画函数,继承自QGraphicsItem
private:
bool m_bupFlag;
QPixmap m_pixUp;
QPixmap m_pixDown;
qreal m_angle;
}; #endif // DRIVEDGRAPH_H
#include "drivedgraph.h"
#include <math.h>
#include <QDebug> const static double PI = 3.1416; DrivedGraph::DrivedGraph()
{
m_bupFlag = true;
m_pixUp = QPixmap(":/Image/up.png");
m_pixDown = QPixmap(":/Image/down.png");
startTimer();
} void DrivedGraph::timerEvent(QTimerEvent *)
{
qreal edgex = scene()->sceneRect().right() + boundingRect().width()/; // 限定右边界
qreal edgetop = scene()->sceneRect().top() + boundingRect().height()/; // 上边界
qreal edgebottom = scene()->sceneRect().bottom() + boundingRect().height()/; // 下边界 qDebug() << "edgex: " << edgex << "edgetop: " << edgetop << "edgebottom: " << edgebottom; 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());
} qDebug() << "pos().x(): " << pos().x() << "pos().y(): " << pos().y() ; m_angle += (qrand()%) / 20.0;
qreal dx = fabs(sin(m_angle*PI)*10.0);
qreal dy = (qrand()%) - 10.0;
setPos(mapToParent(dx,dy));
} QRectF DrivedGraph::boundingRect() const
{
qreal adjust = ;
return QRectF(-m_pixUp.width()/ - adjust,-m_pixUp.height()/ - adjust,
m_pixUp.width() + adjust*,m_pixUp.height() + adjust*);
} void DrivedGraph::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
if (m_bupFlag) {
painter->drawPixmap(boundingRect().topLeft(),m_pixUp);
m_bupFlag = !m_bupFlag;
}
else {
painter->drawPixmap(boundingRect().topLeft(),m_pixDown);
m_bupFlag = !m_bupFlag;
}
}

实现蝴蝶飞舞

#include "butterfly.h"
#include <QApplication> #include "drivedgraph.h" int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Butterfly w;
// w.show(); QGraphicsScene *scene = new QGraphicsScene;
scene->setSceneRect(QRectF(-,-,,));
DrivedGraph *dri = new DrivedGraph;
dri->setPos(-,);
scene->addItem(dri); QGraphicsView *view = new QGraphicsView;
view->setScene(scene);
view->resize(,);
view->show(); return a.exec();
}
05-11 20:49