QT练习

xiaoxiao2021-03-01  8

QT绘制图像

paintEvent()虚函数调用

创建项目的过程不多说

//------------main.cpp main不去动他,项目创建一开始的情况

//------------------mtset.h

#ifndef MYSET_H #define MYSET_H #include <QWidget> namespace Ui { class myset; } class myset : public QWidget { Q_OBJECT public: explicit myset(QWidget *parent = nullptr); ~myset(); protected: //重写绘图事件,如果窗口绘图,必须在绘图事件里面实现 //绘图事件,内部自动调用窗口重绘的时候,窗口状态改变 void paintEvent(QPaintEvent *); private slots: void on_pushButton_clicked(); private: Ui::myset *ui; int x; }; #endif // MYSET_H

//-------------------myset.cpp

#include "myset.h" #include "ui_myset.h" #include<QPainter>//画板 #include<QPen>//画笔 #include<QBrush>//画刷 myset::myset(QWidget *parent) : QWidget(parent), ui(new Ui::myset) { ui->setupUi(this); x=0; } myset::~myset() { delete ui; } void myset::paintEvent(QPaintEvent *)//虚函数,继承绘图基类,名字要一模一样, { // QPainter p(this); QPainter p; p.begin(this);//指定当前窗口为绘图设备 QPen pen; pen.setWidth(2); // pen.setColor(Qt::red); pen.setColor(QColor(14,9,234));//蓝色 // pen.setStyle(Qt::DashLine);//虚线 pen.setStyle(Qt::SolidLine);//圆滑曲线 p.setPen(pen); //画刷,准备填充 QBrush brush; brush.setColor(Qt::blue); brush.setStyle(Qt::Dense1Pattern); p.setBrush(brush); //画背景图 // p.drawPixmap(0,0,width(),height(),QPixmap("../image/2.jpg"));指定起点和长宽 //背景图在前,图形和画笔这些在后,不然会被覆盖 p.drawPixmap(rect(),QPixmap("../image/2.jpg"));//自适应 //画2条直线,首尾坐标 p.drawLine(50,50,50,100);//(50,50)-->(50,100) p.drawLine(50,50,150,50); //画矩形 p.drawRect(150,150,20,30);//起点,长宽 //画圆椭圆 p.drawEllipse(QPoint(70,70),20,20);//圆心,长轴短轴 //画小图形,x变动,从左到右水平移动 p.drawPixmap(x,200,80,80,QPixmap("../image/3.jpg"));//读取上一个文件目录下image文件中的图像 p.end(); } void myset::on_pushButton_clicked() { x+=20;//改变坐标值 if(x>width())//获取当前窗口宽度 { x=0; } //刷新窗口 update();//自动调用paintEvent(QPaintEvent *) }

//-----------ui界面 添加一个按钮,并转到槽函数:即上述代码中的:void myset::on_pushButton_clicked()

//---------------运行结果 按下按钮,佐助移动

转载请注明原文地址: https://www.6miu.com/read-3850075.html

最新回复(0)