最近看了篇文章啊,讲的就是让小球进行移动,可能别人做的是仿真啊,用到了太多的数学函数,什么运动学,各种的,我就想着,自己能不能使用qt实现下这种效果,就是有一个球不停的移动,当碰到边框的时候就进行反方向移动。原理很简单,首先不停的重绘球体位置,其他就是计算的问题了。
直接看代码吧!
.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <qpainter.h>
#include <QTime>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
protected:
void paintEvent(QPaintEvent *event);
protected slots:
void on_timer_timeout();
private:
QTimer *m_time;
int m_X=10;
int m_Y=10;
bool m_bColl=false;
bool m_bYcoll=false;
};
#endif // WIDGET_H
.cpp
#include "widget.h"
#include <QTimer>
#include <qdebug.h>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->resize(800,500);
m_time=new QTimer(this);
m_time->stop();
m_time->setInterval (10) ;//设置定时周期,单位:毫秒
m_time->start();
connect(m_time,SIGNAL(timeout()),this,SLOT(on_timer_timeout()));
}
Widget::~Widget()
{
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter paint(this);
paint.setRenderHint(QPainter::Antialiasing, true);
paint.setPen(QColor("red"));
paint.setBrush(QBrush(QColor("green")));
if(m_bColl==false)
{
m_X=m_X+1;
if(m_bYcoll==false)
{
m_Y=m_Y+1;
paint.drawEllipse(m_X,m_Y,50,50);
}
else
{
m_Y=m_Y-1;
paint.drawEllipse(m_X,m_Y,50,50);
}
}
else
{
m_X=m_X-1;
if(m_bYcoll==false)
{
m_Y=m_Y+1;
paint.drawEllipse(m_X,m_Y,50,50);
}
else
{
m_Y=m_Y-1;
paint.drawEllipse(m_X,m_Y,50,50);
}
}
}
void Widget::on_timer_timeout()
{
if(m_X+50>=this->width())
{
m_bColl=true; //反方向走
}
if(m_X<=0)
{
m_bColl=false;
}
if(m_Y+50>=this->height())
{
m_bYcoll=true;
}
if(m_Y<=0)
{
m_bYcoll=false;
}
update();
}
效果图:
转:https://blog.csdn.net/weixin_43676892/article/details/114140936?spm=1001.2014.3001.5502
标签:Widget,false,qt,windows,小球,50,paint,time,include From: https://www.cnblogs.com/xiaohai123/p/17093153.html