QT-事件-绘图
widget.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #ifndef WIDGET_H #define WIDGET_H #include <QWidget> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public : explicit Widget(QWidget *parent = 0); ~Widget(); //绘图事件 void paintEvent(QPaintEvent *); int posX = 0; private : Ui::Widget *ui; }; #endif // WIDGET_H |
widget.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | #include "widget.h" #include "ui_widget.h" #include <QPainter> //画家类 #include <QTimer> Widget::Widget(QWidget *parent) : QWidget(parent), ui( new Ui::Widget) { ui->setupUi( this ); //点击移动按钮,移动图片 connect(ui->pushButton,&QPushButton::clicked,[=](){ posX+=20; //如果要手动调用绘图事件 用update更新 update(); }); QTimer * timer = new QTimer( this ); timer->start(10); connect(timer,&QTimer::timeout,[=](){ posX++; 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(Qt::cyan); // //设置画刷风格 // brush.setStyle(Qt::Dense7Pattern); // //让画家使用画刷 // painter.setBrush(brush); // //画线 // painter.drawLine(QPoint(0,0) , QPoint(100,100)); // //画圆 椭圆 // painter.drawEllipse( QPoint(100,100) , 50,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(200,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 ); QPixmap pix = QPixmap( ":/Image/Luffy.png" ); //如果超出屏幕 从0开始 if (posX >= this ->width()) { posX = -pix.width(); } painter.drawPixmap(posX,0,pix); } Widget::~Widget() { delete ui; } |
天道酬勤 循序渐进 技压群雄
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!