飛舞的蝴蝶(GraphicsView框架)
一、簡介
GraphicsView框架結構主要包含三個主要的類QGraphicsScene(容器)、QGraphicsView(視圖)、QGraphicsItem(圖形項)。QGraphicsScene本身不可見必須通過與之相連的QGraphicsView視口類來顯示及與外界進行互操作,主要提供項目的操作接口、傳遞事件和管理各個項目狀態;QGraphicsView提供一個可視的窗口,用於顯示場景中的項目,一個場景中可以有多個視口;QGraphicsItem是場景中各個項目的基礎類。
二、關系圖
(1)三者間的關系
(2)坐標系統
QGraphicsScene坐標系是以中心為原點(0,0),QGraphicsView繼承自QWidget以窗口的左上角作為自己坐標系的原點,而QGraphicsItem則有自己的坐標系其paint()函數重畫時以此坐標系為基准。
(3)坐標映射
三個坐標系之間的相互轉換函數及圖形項與圖形項之間的轉換函數。
三、詳解
1、運行圖
2、解析
(1)利用定時器實現QGraphicsItem不停上下飛舞的蝴蝶的動畫效果
- #include <QGraphicsItem>
- #include <QObject>
- class Butterfly : public QObject, public QGraphicsItem
- {
- Q_OBJECT
- public:
- Butterfly();
- void timerEvent(QTimerEvent *);
- QRectF boundingRect() const;
- protected:
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
- private:
- bool up;
- QPixmap pix_up;
- QPixmap pix_down;
- qreal angle;
- };
- static const double PI = 3.14159265358979323846264338327950288419717;
- Butterfly::Butterfly()
- {
- setFlag(QGraphicsItem::ItemIsMovable);
- pix_up.load(":/images/butterfly1.PNG");
- pix_down.load(":/images/butterfly2.PNG");
- up = true;
- startTimer(100);
- }
- QRectF Butterfly::boundingRect() const
- {
- qreal adjust = 8;
- 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;
- }
- // painter->setPen(Qt::NoPen);
- // painter->setBrush(Qt::darkGray);
- // painter->drawEllipse(-7,-7,40,40);
- // painter->setPen(QPen(Qt::black,0));
- // painter->setBrush(flash ? (Qt::red):(Qt::yellow));
- // painter->drawEllipse(-10,-10,40,40);
- }
- void Butterfly::timerEvent(QTimerEvent *)
- {
- // edge controll
- qreal edgex = scene()->sceneRect().right()+boundingRect().width()/2;
- qreal edgetop = scene()->sceneRect().top()+boundingRect().height()/2;
- qreal edgebottom = scene()->sceneRect().bottom()+boundingRect().height()/2;
- //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());
- angle += (qrand()%10)/20.0;
- qreal dx = fabs(sin(angle*PI)*10.0);
- qreal dy = (qrand()%20)-10.0;
- setPos(mapToParent(dx,dy));
- update();
- }
分析:在定時器的timeEvent()中對QGraphicsItem進行重畫,重畫paint()函數中飛舞的蝴蝶是由兩幅圖片組成,蝴蝶的移動邊界做一個限定,dx和dy是相對於蝴蝶的坐標系而言的,調用setPos函數時使用mapToParent()函數映射成場景的坐標。setFlag(QGraphicsItem::ItemIsMovable);使蝴蝶可以通過鼠標移動。
(2)來回移動的星星
- class StarItem : public QGraphicsItem
- {
- public:
- StarItem();
- QRectF boundingRect() const;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
- private:
- QPixmap pix;
- };
- StarItem::StarItem()
- {
- pix.load(":/images/star.png");
- }
- QRectF StarItem::boundingRect() const
- {
- return QRectF(-pix.width()/2,-pix.height()/2,pix.width(),pix.height());
- }
- void
- StarItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
- {
- painter->drawPixmap(boundingRect().topLeft(),pix);
- }
- {
- StarItem *star = new StarItem;
- QGraphicsItemAnimation *anim = new QGraphicsItemAnimation;
- anim->setItem(star);
- QTimeLine *timeLine = new QTimeLine(4000);
- timeLine->setCurveShape(QTimeLine::SineCurve);
- timeLine->setLoopCount(0);
- anim->setTimeLine(timeLine);
- int y = (qrand()%400) - 200;
- for (int i=0; i<400; i++)
- {
- anim->setPosAt(i/400.0, QPointF(i-200,y));
- }
- timeLine->start();
- scene->addItem(star);
- }
分析:利用QGraphicsItemAnimation類和QTimeLine實現項目的動畫效果(也可使用定時器QTimer結合重繪函數來實現)。
(3)簡單正方形
- {
- QGraphicsRectItem *item = new QGraphicsRectItem(QRectF(0,0,60,60));
- QPen pen;
- pen.setWidth(3);
- pen.setColor(QColor(qrand()%256,qrand()%256,qrand()%256));
- item->setPen(pen);
- item->setBrush(QColor(qrand()%256,qrand()%256,qrand()%256));
- item->setFlag(QGraphicsItem::ItemIsMovable);
- scene->addItem(item);
- //item->setPos((qrand()%int(scene->sceneRect().width()))-200,(qrand()%int(scene->sceneRect().height()))-200);
- item->setPos(-200, -200);
- }
分析:利用繼承QGraphicsItem的類QGraphicsRectItem添加一個正方形的圖形項。
注意編譯時會出現如下警告:
Warning::Class Butterfly imlements the interface QGraphicsItem but does not list it in Q_INTERFACES ;qobject_cast to QGraphicsItem will not work
原因:
QGraphicsItem的paint方法是在item被重繪時調用的,除了調用這個接口函數外,他還需要調用另外幾個接口函數,你是不是在類中沒有寫呀?
需要添加的函數列表:
QRectF boundingRect() const;
QPainterPath shape() const;
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent * event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent * event);
一、簡介
GraphicsView支持事件傳播體系結構,可以使圖元在場景scene中得到提高了已被的精確交互能力。圖形視圖框架中的事件都是首先由視圖進行接收,然后傳遞給場景,再由場景給相應的圖形項。
對於鍵盤鼠標事件,scene會傳遞給獲得焦點的圖形項。如果場景沒有獲得焦點,那鍵盤事件會丟棄;如果調用場景setFocus()或者場景中的一個圖形項獲得了焦點,那么場景會自動獲得焦點;如果場景丟失了焦點(如調用clearFocus())而其中一個圖形項獲得焦點那場景會保存這個圖形項的焦點信息。
圖形項默認無法接收懸停事件,可以使用QGraphicsItem的setAcceptHoverEvents()函數使圖形項可以接收懸停事件。
二、運行圖
(1)五個圖形項的運行圖如下圖所示。
三、詳解
1、QGraphicsScene
- #ifndef MYSCENE_H
- #define MYSCENE_H
- #include <QGraphicsScene>
- #include <QGraphicsSceneMouseEvent>
- #include <QPaintEvent>
- #include <QKeyEvent>
- class MyScene : public QGraphicsScene
- {
- Q_OBJECT
- public:
- explicit MyScene(QObject *parent = 0);
- protected:
- void keyPressEvent(QKeyEvent *event);
- void mousePressEvent(QGraphicsSceneMouseEvent *event);
- signals:
- public slots:
- };
- #endif // MYSCENE_H
- #include "myscene.h"
- MyScene::MyScene(QObject *parent) :
- QGraphicsScene(parent)
- {
- clearFocus();
- }
- void MyScene::keyPressEvent(QKeyEvent *event)
- {
- qDebug("*********MyScene::keyPressEvent***************");
- return QGraphicsScene::keyPressEvent(event);
- }
- void MyScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
- {
- qDebug("*********MyScene::mousePressEvent***************");
- QGraphicsScene::mousePressEvent(event);
- }
2、QGraphicsView
- #ifndef MYVIEW_H
- #define MYVIEW_H
- #include <QGraphicsView>
- class MyView : public QGraphicsView
- {
- Q_OBJECT
- public:
- explicit MyView(QWidget *parent = 0);
- protected:
- void keyPressEvent(QKeyEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void paintEvent(QPaintEvent * event);
- void mouseMoveEvent(QMouseEvent *event);
- signals:
- public slots:
- };
- #endif // MYVIEW_H
- #include "myview.h"
- #include <QKeyEvent>
- MyView::MyView(QWidget *parent) :
- QGraphicsView(parent)
- {
- }
- void MyView::keyPressEvent(QKeyEvent *event)
- {
- qDebug("*********MyView::keyPressEvent***************");
- switch (event->key())
- {
- case Qt::Key_Left :
- scale(1.2, 1.2);
- break;
- case Qt::Key_Right :
- scale(1 / 1.2, 1 / 1.2);
- break;
- case Qt::Key_Up :
- rotate(30);
- break;
- }
- QGraphicsView::keyPressEvent(event);
- }
- void MyView::mousePressEvent(QMouseEvent *event)
- {
- qDebug("************MyView::mousePressEvent*****************");
- QGraphicsView::mousePressEvent(event);
- }
- void MyView::paintEvent(QPaintEvent *event)
- {
- qDebug("************MyView::paintEvent*****************");
- QGraphicsView::paintEvent(event);
- }
- void MyView::mouseMoveEvent(QMouseEvent *event)
- {
- //qDebug("************MyView::mouseMoveEvent*****************");
- QGraphicsView::mouseMoveEvent(event);
- }
3、QGraphicsItem
- #ifndef MYITEM_H
- #define MYITEM_H
- #include <QGraphicsItem>
- #include <QGraphicsSceneEvent>
- class MyItem : public QGraphicsItem
- {
- public:
- MyItem();
- QRectF boundingRect() const;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
- QWidget *widget);
- void setColor(const QColor &color) { brushColor = color; }
- protected:
- void keyPressEvent(QKeyEvent *event);
- void mousePressEvent(QGraphicsSceneMouseEvent *event);
- void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
- void hoverLeaveEvent (QGraphicsSceneHoverEvent * event);
- void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
- private:
- QColor brushColor;
- };
- #endif // MYITEM_H
- #include "myitem.h"
- #include <QPainter>
- #include <QCursor>
- #include <QKeyEvent>
- #include <QGraphicsSceneHoverEvent>
- #include <QGraphicsSceneContextMenuEvent>
- #include <QMenu>
- MyItem::MyItem()
- {
- brushColor = Qt::red;
- setFlag(QGraphicsItem::ItemIsFocusable);
- setFlag(QGraphicsItem::ItemIsMovable);
- //setAcceptHoverEvents(true);
- }
- QRectF MyItem::boundingRect() const
- {
- qreal adjust = 0.5;
- return QRectF(-10 - adjust, -10 - adjust,
- 20 + adjust, 20 + adjust);
- }
- void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
- QWidget *widget)
- { qDebug("************MyItem::paint*****************");
- if(hasFocus()) {
- painter->setPen(QPen(QColor(255,255,255,200)));
- } else {
- painter->setPen(QPen(QColor(100,100,100,100)));
- }
- painter->setBrush(brushColor);
- painter->drawRect(-10, -10, 20, 20);
- }
- // 鼠標按下事件處理函數,設置被點擊的圖形項獲得焦點,並改變光標外觀
- void MyItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
- {
- qDebug("************MyItem::mousePressEvent*****************");
- setFocus();
- setCursor(Qt::ClosedHandCursor);
- }
- // 鍵盤按下事件處理函數,判斷是否是向下方向鍵,如果是,則向下移動圖形項
- void MyItem::keyPressEvent(QKeyEvent *event)
- {
- qDebug("************MyItem::keyPressEvent*****************");
- if(event->key() == Qt::Key_Down)
- moveBy(0, 10);
- }
- // 懸停事件處理函數,設置光標外觀和提示
- void MyItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
- {
- qDebug("************MyItem::hoverEnterEvent*****************");
- setCursor(Qt::OpenHandCursor);
- setToolTip("I am item");
- }
- void MyItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
- {
- qDebug("************MyItem::hoverLeaveEvent*****************");
- setCursor(Qt::ArrowCursor);
- }
- // 右鍵菜單事件處理函數,為圖形項添加一個右鍵菜單
- void MyItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
- {
- QMenu menu;
- QAction *moveAction = menu.addAction("move back");
- QAction *actAction = menu.addAction("test");
- QAction *selectedAction = menu.exec(event->screenPos());
- if(selectedAction == moveAction) {
- setPos(0, 0);
- }
- }
- void MyItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
- {
- qDebug("************MyItem::mouseMoveEvent*****************");
- QGraphicsItem::mouseMoveEvent(event);
- }
4、main及運行
- #include <QApplication>
- #include "myitem.h"
- #include "myview.h"
- #include "myscene.h"
- #include <QTime>
- int main(int argc,char* argv[ ])
- {
- QApplication app(argc,argv);
- qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
- MyScene scene;
- scene.setSceneRect(-200, -150, 400, 300);
- for(int i = 0; i < 5; ++i) {
- MyItem *item = new MyItem;
- item->setColor(QColor(qrand() % 256, qrand() % 256, qrand() % 256));
- item->setPos(i * 50 - 90, -50);
- scene.addItem(item);
- }
- MyView view;
- view.setScene(&scene);
- view.setBackgroundBrush(QPixmap(":/background.png"));
- view.show();
- return app.exec();
- }
分析:keyPressEvent鍵盤按下事件由View—Scene—Item
分析:mousePressEven鼠標按下事件由View—Scene—Item
分析:事件項Item沒有獲得焦點時,mousePressEven鼠標按下事件只由View傳遞到Scene。
分析:事件項Item的懸停事件,在構造函數中設置了setAcceptHoverEvents(true)。