Qt5 绘图 - 利用 QPixmap 和 QPainter 实现在 paintevent() 函数外绘图
Qt 的绘图操作,是使用 QPainter 在 paintevent() 函数中进行的,所有绘图操作都要放进函数 paintevent() 中。
在实际编程中,例如编写计算机图形学作业——编写简易绘图库时,为了封装便利,需要将绘图操作从 paintevent() 中外提。这时候 QPixmap 便派上用场了:在 paintevent() 之外,将所有绘图操作绘制在 QPixmap上,而在paintevent() 之内,仅绘制 QPixmap 即可。
开发环境
- Qt版本:5.10
- 编译器:MSVC2017
- 操作系统:Windows 10
相关代码
文件:draw.h
#ifndef DRAW_H
#define DRAW_H
// 添加头文件
#include <QColor>
#include <QPixmap>
#include <QPainter>
#include <QDialog>
namespace Ui {
class Draw;
}
class Draw : public QDialog {
Q_OBJECT
public:
explicit Draw(QWidget *parent = 0);
~Draw();
// 添加函数
void paintEvent(QPaintEvent *);
void draw_point(int const x, int const y, QColor const c, int const w);
private:
Ui::Draw *ui;
// 添加成员变量
QPixmap Pix;
};
#endif // DRAW_H
文件:draw.cpp
#include "draw.h"
#include "ui_draw.h"
// 定义窗口长宽和标题
#define WIN_WIGHT 800
#define WIN_HEIGHT 600
#define WIN_TITLE "画图测试"
Draw::Draw(QWidget *parent) : QDialog(parent), ui(new Ui::Draw) {
ui->setupUi(this);
// 设置窗口
setFixedSize(WIN_WIGHT, WIN_HEIGHT);
setWindowTitle(WIN_TITLE);
setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint);
// 初始化QPixmap
Pix = QPixmap(WIN_WIGHT, WIN_HEIGHT);
Pix.fill(Qt::white);
}
Draw::~Draw() {
delete ui;
}
// 画图任务事件
void Draw::paintEvent(QPaintEvent *) {
QPainter Painter(this);
Painter.drawPixmap(0, 0, WIN_WIGHT, WIN_HEIGHT,Pix);
}
void Draw::draw_point(int const x, int const y, QColor const c, int const w) {
// 在QPixmap上画图
QPainter Painter(&Pix);
Painter.setPen(QPen(c, w));
Painter.drawPoint(x, y);
}
文件:main.cpp
#include "draw.h"
#include <QApplication>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Draw w;
w.show();
// 尝试调用
w.draw_point(10,10,QColor(10,20,20), 10);
w.draw_point(200,10,QColor(10,203,20), 5);
return a.exec();
}