图形视图(飞舞的蝴蝶:场景、图元、视图的简单使用)

飞舞的蝴蝶

  • 程序
    • 图元设置
    • 场景、视图设置
  • 效果展示

程序

图元设置

.h
#ifndef BUTTERFLY_H
#define BUTTERFLY_H

#include 
#include 
#include 
#include 
#include 

class Butterfly : public QObject,public QGraphicsItem
{
    Q_OBJECT
public:
    explicit Butterfly(QObject *parent = nullptr);
    void timerEvent(QTimerEvent*);//定时器
    QRectF boundingRect() const;//为图元限定区域范围,所有继承自QGraphicsItem的自定义图元都必须事先次函数
signals:

public slots:
protected:
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);//重绘函数
private:
    bool up;
    QPixmap pix_up;
    QPixmap pix_down;
    qreal angle;
};

#endif // BUTTERFLY_H
.cpp
#include "butterfly.h"
#include 
#include 
const static double PI=3.1416;

Butterfly::Butterfly(QObject *parent) : QObject(parent)
{
    up=true;
    pix_up.load("up.png");
    pix_down.load("down.png");
    startTimer(100);
}
QRectF Butterfly::boundingRect() const//为图元限定区域范围
{
    qreal adjust =2;
    return QRectF(-pix_up.width()/2-adjust,-pix_up.height()/2-adjust,
                  pix_up.width()+adjust*2,pix_up.height()+adjust*2);
}

void Butterfly::timertest()
{
    qDebug()<<"c";
}
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;
    }
}
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;//限定蝴蝶飞舞的下边界
    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));
}



场景、视图设置

.cpp
#include "mainwindow.h"
#include 
#include 
#include 
#include "butterfly.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    QGraphicsScene *scene = new QGraphicsScene;
    scene->setSceneRect(QRectF(-200,-200,400,400));//设置场景范围
    Butterfly *butterfly = new Butterfly;
    butterfly->setPos(-100,0);//设置图元出现坐标
    scene->addItem(butterfly);//将图元加入场景
    QGraphicsView *view = new QGraphicsView;
    view->setScene(scene);//视图显示场景
    view->resize(400,400);
    view->show();
    //w.show();

    return a.exec();
}

效果展示

图形视图(飞舞的蝴蝶:场景、图元、视图的简单使用)_第1张图片

你可能感兴趣的:(QT学习)