学习QT的第六天
程序员文章站
2022-06-06 13:58:40
...
飞舞的蝴蝶
代码结构:
butterfly.h
#include <QObject>
#include <QGraphicsItem>
#include <QPainter>
#include <QGraphicsScene>
#include <QGraphicsView>
class Butterfly : public QObject,public QGraphicsItem
{
Q_OBJECT
public:
explicit Butterfly(QObject *parent = 0);
void timerEvent(QTimerEvent *); //定时器
QRectF boundingRect() const; //为图元限定范围
signals:
public slots:
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); //重绘函数
private:
bool up; //
QPixmap pix_up; //用于表示两幅蝴蝶的图片
QPixmap pix_down;
qreal angle;
};
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
};
#endif // MAINWINDOW_H
butterfly.cpp
#include "butterfly.h"
#include <math.h>
const static double PI=3.1416;
Butterfly::Butterfly(QObject *parent) : QObject(parent)
{
up = true; //给标志蝴蝶翅膀位置的变量赋初值
pix_up.load("up.jpg"); //调用QPixmap的load()函数加载所用到的图片
pix_down.load("down.jpg");
startTimer(100); //启动定时器,并设置时间间隔为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::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));
}
mainwindow.cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
};
#endif // MAINWINDOW_H
mian.cpp
#include "mainwindow.h"
#include"butterfly.h"
#include <QApplication>
#include<QGraphicsScene>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
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();
return a.exec();
}
上一篇: 【备战秋招】数据库
下一篇: Python实现二叉搜索树的方法