Qt實用技巧:QPainterPath繪圖路徑(多次畫同樣的圖形集合)
阿新 • • 發佈:2019-02-06
需求
根據配置檔案,可不改變程式只調整配置檔案可調整主頁面上的字串。
原理
1.讀取檔案,固定格式(檔案在本文章中省略)
2.寫一串字元,使用QPainterPath
3.注意QPainter的時候,需要設定QPen和QBrush
程式碼
第一部分程式碼,儲存一個QPainterPath
MainWindow::MainWindow(QWidget*parent):
QMainWindow(parent),
ui(newUi::MainWindow)
{
ui->setupUi(this);
//initashapeItem
QColorcolor(Qt::red);
QFontfont("黑體",24,QFont::Bold,true);
QPointpoint(200,200);
QStringstr="測試QPaintPath";
QPainterPathpainterPath;
painterPath.addText(QPointF(0,0),
QFont("黑體",24,QFont::Bold,true),
tr("測試QPaintPath"));
_pShapeItem=newShapeItem();
_pShapeItem->setColor(color);
_pShapeItem->setFont(font);
_pShapeItem->setPosition(point);
_pShapeItem->setText(str);
_pShapeItem->setPainterPath(painterPath);
}
第二部分程式碼,畫出圖形
void MainWindow::paintEvent(QPaintEvent *) { QPainter painter(this); // 儲存之前的painter painter.save(); // 設定該螢幕座標點為座標系原點(0,0) 注意:必須要重新設定畫筆和畫刷 painter.setPen(_pShapeItem->getColor()); // 字型外部輪廓線條 painter.setBrush(_pShapeItem->getColor()); // 字型輪廓內部顏色 painter.translate(_pShapeItem->getPosition()); // 寫字型的位置 painter.drawPath(_pShapeItem->getPainterPath()); // 畫 // 回覆之前的painter painter.restore(); }
第三部分程式碼,標頭檔案ShapeItem.h
#ifndef SHAPEITEM_H
#define SHAPEITEM_H
#include <QPainterPath>
#include <QColor>
#include <QFont>
class QPainterPath;
class QPoint;
class QColor;
class QString;
class QFont;
class ShapeItem
{
public:
ShapeItem();
public:
void setPainterPath(QPainterPath &path) { _path = path; }
void setPosition(QPoint &position) { _position = position; }
void setColor(QColor &color) { _color = color; }
void setText(QString &text) { _text = text; }
void setFont(QFont &font) { _font = font; }
public:
QPainterPath getPainterPath() const { return _path; }
QPoint getPosition() const { return _position; }
QColor getColor() const { return _color; }
QString getText() const { return _text; }
QFont getFont() const { return _font; }
private:
QPainterPath _path;
QPoint _position;
QColor _color;
QString _text;
QFont _font;
};
#endif // SHAPEITEM_H
第四部分程式碼,原始檔ShapeItem.cpp
#include "shapeitem.h"
ShapeItem::ShapeItem()
{
}