如何用更宽的虚线绘制现有的虚线?

How to draw over an existing dotted line with a wider one?

我想在现有的虚线(左黑)上画一条巨石线(右绿)来模拟选择效果,
但是粗线的笔划与原来的笔画不对齐
即使它们是使用相同的 start/end 点 p1p2 绘制的:

代码如下:

const QPointF p1{};
const QPointF p2{};

// draw thin black line
QPen blackPen;
blackPen.setWidth(10);
blackPen.setColor(Qt::black);
blackPen.setStyle(Qt::DotLine);

painter->setPen(blackPen);
painter->setBrush(Qt::NoBrush);
painter->drawLine(p1, p2);

// draw bold green line using the same points
QPen boldGreenPen;
boldGreenPen.setWidth(12);
boldGreenPen.setColor(Qt::green);
boldGreenPen.setStyle(Qt::DotLine);

painter->setPen(boldGreenPen);
painter->setBrush(Qt::NoBrush);
painter->drawLine(p1, p2);

是否可以实现预期的行为?

根据Qt docs

The dash pattern is specified in units of the pens width

这意味着我们必须像这样计算两条线的宽度之间的比率:

QPen pen;
const double penWidth(pen.widthF());
const auto penDashPattern(pen.dashPattern());

QPen boldPen(pen);
const double boldPenWidth(penWidth + 2);
auto boldPenDashPattern(boldPen.dashPattern());

const double ratio(penWidth / boldPenWidth);
for (auto & pattern : boldPenDashPattern)
{
    pattern *= ratio;
}

boldPen.setWidthF(boldPenWidth);
boldPen.setDashPattern(boldPenDashPattern);

painter->setPen(boldPen);

这给了我们想要的结果