Now, a more generic solution for n colors (I know it has too many parameters, it's just an idea). The trick is done creating a single dash-pattern, and moving it using QPen::setDashOffset for each color:
void drawMultiColorDashedLine(QPainter& painter, const QLine& line,
int length, int gap, int width,
const QList<QColor>& colors, bool startWithGap = false) {
const int n = colors.count();
const int initialGap = startWithGap ? gap : 0;
QPen pen;
pen.setWidth(width);
pen.setDashPattern({ (qreal)length, (qreal)(gap * n + length * (n - 1)) });
for (int ii = 0; ii < n; ++ii) {
pen.setColor(colors[ii]);
pen.setDashOffset(-ii * (length + gap) - initialGap);
painter.setPen(pen);
painter.drawLine(line);
}
}
Developing the idea of @goug, you can do something like:
Now, a more generic solution for
n
colors (I know it has too many parameters, it's just an idea). The trick is done creating a single dash-pattern, and moving it usingQPen::setDashOffset
for each color:So they can be called:
The full working example is available at GitHub