手动调用绘图事件
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
//绘图事件
void paintEvent(QPaintEvent *);
int posX=0;
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QBrush>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//点击移动按钮
connect(ui->pushButton,&QPushButton::clicked,[=](){
//如果要手动调用绘图事件,用update更新
posX+=20;
update();
});
}
//绘图事件
void Widget::paintEvent(QPaintEvent *)
{
/*
//实例化画家类 this指定的是绘图的设备
QPainter painter(this);
//设置画笔
QPen pen(QColor(255,0,0));
//设置画笔宽度
pen.setWidth(3);
//设置画笔风格
pen.setStyle(Qt::DotLine);
//让画家使用这个笔
painter.setPen(pen);
//设置画刷
//QBrush brush(QColor(0,255,0));
QBrush brush(Qt::green);
//设置画刷风格
brush.setStyle(Qt::Dense7Pattern);
//让画家使用画刷
painter.setBrush(brush);
painter.drawLine(QPoint(0,0),QPoint(100,100)); //画线
painter.drawEllipse(QPoint(100,100),50,50);//画圆(椭圆100 50)
painter.drawRect(QRect(20,20,50,50)); //画矩形
painter.drawText(QRect(10,200,150,50),"好好学习,天天向上");//画文字
*/
////高级设置
/* QPainter painter(this);
//圆形
painter.drawEllipse(QPoint(100,50),50,50);
//设置 抗锯齿能力 效率较低
painter.setRenderHint(QPainter::Antialiasing);
painter.drawEllipse(QPoint(250,50),50,50);
*/
/*
//矩形
painter.drawRect(QRect(20,20,50,50));
painter.translate(100,0);//移动画家
//保存画家状态
painter.save();
painter.drawRect(QRect(20,20,50,50));
painter.translate(100,0);//移动画家
painter.restore();//还原画家保存状态
painter.drawRect(QRect(20,20,50,50));
*/
////利用画家画资源图片////
QPainter painter(this);
//如果超出了屏幕 从0开始
if(posX>this->width())
{
posX=0;
}
painter.drawPixmap(posX,0,QPixmap(":/rec/jb.jpg"));
}
Widget::~Widget()
{
delete ui;
}
标签:Widget,20,QT,50,P38,ui,100,完整版,painter
From: https://www.cnblogs.com/Vivian-0918/p/17577748.html