填充
基本原理
- 在
QPainter
中使用的函数
- 使用画刷填充路径,填充后没有轮廓线条
fillPath(const QPainterPath &path, const QBrush &brush)
- 使用该函数可绘制由fillPath()填充后,路径的轮廓线路
strokePath(const QPainterPath &path, const QPen &pen)
- 使用画刷brush填充矩形区域,填充后没有轮廓线条
fillRect(const QRectF &rectangle, const QBrush &brush)
fillRect(const QRect &rectangle, const QBrush &brush)
fillRect(int x, int y, int width, int height, const QBrush &brush)
- 使用颜色color填充矩形区域,填充后没有轮廓线条
fillRect(const QRectF &rectangle, const QColor &color)
fillRect(const QRect &rectangle, const QColor &color)
fillRect(int x, int y, int width, int height, const QColor &color)
- 使用预定义的全局颜色color填充矩形区域,填充后没有轮廓线条
fillRect(int x, int y, int width, int height, Qt::GlobalColor color)
fillRect(const QRect &rectangle, Qt::GlobalColor color)
fillRect(const QRectF &rectangle, Qt::GlobalColor color)
- 使用画刷样式填充矩形区域,填充后没有轮廓线条
fillRect(int x, int y, int width, int height, Qt::BrushStyle style)
fillRect(const QRect &rectangle, Qt::BrushStyle style)
fillRect(const QRectF &rectangle, Qt::BrushStyle style)
- 擦除矩形区域的填充
eraseRect(const QRectF &rectangle)
eraseRect(int x, int y, int width, int height)
eraseRect(const QRect &rectangle)
- 画刷原点。影响画刷纹理图案和渐变
void setBrushOrigin(const QPointF &position)
void setBrushOrigin(const QPoint &position)
void setBrushOrigin(int x, int y)
QPoint brushOrigin() const
- 背景画刷(透明模式(默认)下不起作用)
void setBackground(const QBrush &brush)
const QBrush &background() const
- 背景模式
void setBackgroundMode(Qt::BGMode mode)
Qt::BGMode backgroundMode() const
- 填充区域
- 当绘制封闭的形状时,在其内部可以填充各种颜色、图案等属性。但并不是所有封闭形状都可以被填充。
- 使用
QPainter::drawLine()
函数绘制的封闭形状就不能被填充 - 使用
QPainter
对象绘制的直线、弧不是填充区域 - 使用
QPainter
对象绘制的矩形、椭圆、弦、扇形是填充区域 - 使用路径
QPainterPath
与使用QPen
绘制的图形和轮廓也是填充区域 - 填充区域不一定有轮廓线,比如使用Qt::NoPen画刷样式绘制的填充区域就没有轮廓线
- 使用画刷可向填充区域中填充颜色、图案、渐变等属性
- 要填充虚线的空白和字体背景,需要使用
setBackground()
函数设置背景画刷,且还需使用setBackgroundMode()
函数把背景模式设置为Qt::OpaqueMode(不透明)
- 画刷原点对于使用渐变填充的区域和使用画刷填充纹理图案时会有一定影响
示例
#ifndef WIDGET_H
#define WIDGET_H
#include <QtWidgets>
#include <QLinearGradient>
class DrawGradient :public QWidget
{
Q_OBJECT
private:
void init(){
}
protected:
void paintEvent(QPaintEvent *event) override{
Q_UNUSED(event)
QPainter painter;
painter.begin(this);
QLinearGradient gradient(QPointF(11,11),QPointF(155,11));
gradient.setColorAt(0,QColor(111,255,255));
gradient.setColorAt(0.5,QColor(111,1,1));
gradient.setColorAt(1,QColor(255,255,1));
gradient.setSpread(QGradient::RepeatSpread);
QBrush gradientBrush(gradient) , backgroundBrush(Qt::green);
QPen pen;
pen.setCapStyle(Qt::FlatCap);
pen.setWidth(10);
pen.setStyle(Qt::DashLine);
pen.setBrush(gradientBrush);
painter.setPen(pen);
QFont font;
font.setPointSize(33);
painter.setFont(font);
painter.setBackground(backgroundBrush);
painter.setBackgroundMode(Qt::OpaqueMode);
painter.drawText(11,111,"渐变字体");
painter.setBrushOrigin(50,111);
painter.drawRect(11,11,333,222);
painter.end();
}
public:
DrawGradient(QWidget *p =nullptr) :QWidget(p){ init(); }
};
#endif