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 = );
~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(, , 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(,,QColor(,,), );
w.draw_point(,,QColor(,,), );
return a.exec();
}
運作結果
