widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPaintEvent> //绘图事件
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
void paintEvent(QPaintEvent *event); //重写绘图事件
void timerEvent(QTimerEvent *event);
private:
int xPos; //x轴坐标
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include <QPainter> //画家
#include <QPen> //画笔
#include <QBrush> //画刷
#include <QTimerEvent>
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent),xPos(0) //x轴坐标初始化为0
{
setWindowTitle("绘图");
setFixedSize(1000,800);
//QWidget自带一个定时器
startTimer(1000);
}
Widget::~Widget()
{
}
//重写绘图事件
void Widget::paintEvent(QPaintEvent *event)
{
//将widget主窗口作为画布
QPainter painter(this);
//设置画笔颜色为蓝色
QPen pen(QColor(0,0,255)); //三基色:红绿蓝
//设置画笔的粗细
pen.setWidth(2);
//设置画笔风格:点线
pen.setStyle(Qt::DotLine);
//设置画刷颜色为红色:填充
QBrush brush(QColor(255,0,0));
//设置画刷风格
brush.setStyle(Qt::Dense6Pattern);
painter.setPen(pen);
painter.setBrush(brush);
//画一条线,起始x轴y轴,终点x轴y轴
painter.drawLine(0,0,100,100);
//画矩形,起始x轴y轴,宽200高100
painter.drawRect(100,100,200,100);
//画圆
painter.drawEllipse(400,100,100,100);
//画椭圆
painter.drawEllipse(500,100,400,100);
//画浮点数的点
const QPointF points[4] = {
QPointF(10.1,80.2),
QPointF(20.1,10.5),
QPointF(70.6,40.7),
QPointF(90.2,100.6)
};
//画多边形,多个点连接
painter.drawPolygon(points,4);
//画图片
painter.drawPixmap(xPos++*50,400,QPixmap(":/images/luffy.png"));
if(xPos*50 > this->width()) //图片移动
{
xPos = 0;
}
}
void Widget::timerEvent(QTimerEvent *event)
{
qDebug() << "超时事件";
//手动刷新,让窗口重绘,产生绘图事件
this->update();
}
mian.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
资源文件
结果