QPen 类定义如何以 QPainter 绘制线条和形状的轮廓。
Pen样式定义线型。 Brush用于填充用笔生成的笔触。 使用 QBrush 类来指定填充样式。 cap 样式决定了可以使用 QPainter 绘制的线端帽,而 join 样式描述了如何绘制两条线之间的连接。 笔宽可以以整数 (width()) 和浮点 (widthF()) 精度指定。 线宽为零表示cosmetic笔。 这意味着画笔的宽度始终绘制为一个像素宽,与绘制器上设置的变换无关。
例子:
QPainter painter(this);
QPen pen; // creates a default pen
pen.setStyle(Qt::DashDotLine);
pen.setWidth(3);
pen.setBrush(Qt::green);
pen.setCapStyle(Qt::RoundCap);
pen.setJoinStyle(Qt::RoundJoin);
painter.setPen(pen);
源码解析:
1.QPen();
QPen::QPen()
{
d = defaultPenInstance()->pen;
d->ref.ref();
}
2. void setStyle(Qt::PenStyle);
void QPen::setStyle(Qt::PenStyle s)
{
if (d->style == s)
return;
detach();
d->style = s;
QPenData *dd = static_cast(d);
dd->dashPattern.clear();
dd->dashOffset = 0;
}
void QPen::detach()
{
if (d->ref.loadRelaxed() == 1)
return;
QPenData *x = new QPenData(*static_cast(d));
if (!d->ref.deref())
delete d;
x->ref.storeRelaxed(1);
d = x;
}
先解绑原先的style,再设置新的style.
3.Qt::PenStyle style() const;
Qt::PenStyle QPen::style() const
{
return d->style;
}
4. void setWidth(int width);
void QPen::setWidth(int width)
{
if (width < 0)
qWarning("QPen::setWidth: Setting a pen width with a negative value is not defined");
if ((qreal)width == d->width)
return;
detach();
d->width = width;
}
5. int width() const;
int QPen::width() const
{
return qRound(d->width);
}
6.QBrush brush() const;
QBrush QPen::brush() const
{
return d->brush;
}
7.void setBrush(const QBrush &brush);
void QPen::setBrush(const QBrush &brush)
{
detach();
d->brush = brush;
}
8.Qt::PenCapStyle capStyle() const;
Qt::PenCapStyle QPen::capStyle() const
{
return d->capStyle;
}
9.void setCapStyle(Qt::PenCapStyle pcs);
void QPen::setCapStyle(Qt::PenCapStyle c)
{
if (d->capStyle == c)
return;
detach();
d->capStyle = c;
}
10.Qt::PenJoinStyle joinStyle() const;
Qt::PenJoinStyle QPen::joinStyle() const
{
return d->joinStyle;
}
11.void setJoinStyle(Qt::PenJoinStyle pcs);
void QPen::setJoinStyle(Qt::PenJoinStyle j)
{
if (d->joinStyle == j)
return;
detach();
d->joinStyle = j;
}