avatar

Qt绘图
  • 绘图设备:
    • QPixmap:针对屏幕进行优化,和平台相关,不能对图片进行修改
    • QImage:和平台无关,可以对图片进行修改,在线程中绘图
    • QPicture:将绘图状态保存为一个二进制文件

用法相同,但作用有区别


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();

protected:
//重写绘图事件,虚函数
//如果在窗口绘图,不许放在绘图事件里实现
//绘图事件内部自动调用,窗口需要重绘的时候(状态改变)
void paintEvent(QPaintEvent*);


private slots:
void on_pushButton_clicked();

private:
Ui::MainWindow *ui;
int x;
int y;
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
#include <QDebug>
#include <QBrush>


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
x=0;

}

MainWindow::~MainWindow()
{
delete ui;
}


void MainWindow::paintEvent(QPaintEvent* )
{
//QPainter p(this);与下面两个等价
QPainter p;//创建画家对象
p.begin(this);//指定当前窗口为绘图设备
//绘图操作
//p.drawxxx();各种绘图样式
//画背景图
//p.drawPixmap(0,0,width(),height(),QPixmap("E:/study/qt/code/bb6a99488e1385c992bf0ad07392ccaa.jpeg"));
p.drawPixmap(rect(),QPixmap("E:/study/qt/code/bb6a99488e1385c992bf0ad07392ccaa.jpeg"));


//自定义画笔
QPen pen;
pen.setWidth(5);//设置线宽
//pen.setColor(Qt::red);
pen.setColor(QColor(14,9,234));//RGB设置颜色
pen.setStyle(Qt::SolidLine);//设置风格
//把画笔交给画家
p.setPen(pen);
//画直线
p.drawLine(50,50,150,50);
p.drawLine(50,50,50,150);
//创建画刷对象
QBrush brush;
brush.setColor(Qt::red);
brush.setStyle(Qt::Dense1Pattern);//设置样式
p.setBrush(brush);
//画矩形
p.drawRect(150,150,100,50);
//画圆形
p.drawEllipse(QPoint(150,150),50,25);
//画笑脸
p.drawPixmap(x,500,300,200,QPixmap("C:/Users/lxm/Pictures/Saved Pictures/明信片16.jpg"));


p.end();
}

void MainWindow::on_pushButton_clicked()
{
x+=20;
if(x>width())
{
x=0;
}
//刷新窗口,让整个窗口重绘
update();//简介调用paintEvent()
}

  • 保存图片
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QPainter>


    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    ui->setupUi(this);
    //绘图设备,400*300
    QPixmap pixmap(400,300);
    QPainter p(&pixmap);
    //填充白色
    p.fillRect(0,0,400,300,QBrush(Qt::white));
    p.drawPixmap(0,0,80,80,QPixmap("C:/Users/lxm/Pictures/3e40d65390723ce873e88385b4d57bff.jpeg"));
    //保存图片
    pixmap.save("../pixmap.png");
    }

    MainWindow::~MainWindow()
    {
    delete ui;
    }
Author: Michelle19l
Link: https://gitee.com/michelle19l/michelle19l/2019/08/31/Qt/Qt绘图/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
    微信
  • 支付寶
    支付寶