首页 > 解决方案 > 使用 QPen 的带有虚线图案的多色虚线

问题描述

我需要绘制一条多色线,QPen其中可能包含多达三种颜色的虚线图案。

不同的颜色应该在一条线上。

关于如何实现它的任何建议?

谢谢你。

标签: c++qtqpen

解决方案


发展@goug的想法,你可以做这样的事情:

void drawWithManualDashedLine(QPainter& painter, const QLine& line) {
  const int scale = 10;

  QPen pen;
  pen.setWidth(3);

  pen.setColor(Qt::red);
  pen.setDashPattern({ 0.0, 1.0 * scale, 1.0 * scale, 7.0 * scale });
  painter.setPen(pen);
  painter.drawLine(line);

  pen.setColor(Qt::green);
  pen.setDashPattern({ 0.0, 4.0 * scale, 1.0 * scale, 4.0 * scale});
  painter.setPen(pen);
  painter.drawLine(line);

  pen.setColor(Qt::blue);
  pen.setDashPattern({ 0.0, 7.0 * scale, 1.0 * scale, 1.0 *scale });
  painter.setPen(pen);
  painter.drawLine(line);    
}

现在,一个更通用的n颜色解决方案(我知道它有太多参数,这只是一个想法)。诀窍是创建一个单一的破折号图案,并为每种颜色移动它:QPen::setDashOffset

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);
  }
}

所以他们可以被称为:

void Widget::paintEvent(QPaintEvent*)
{
  QPainter painter(this);

  const QLine line1(0, height() / 3, width(), height() / 3);
  drawMultiColorDashedLine(painter, line1, 10, 20, 3, { Qt::blue, Qt::yellow }, true);

  const QLine line2(0, height() / 2, width(), height() / 2);
  drawWithManualDashedLine(painter, line2);

  const QLine line3(0, 2 * height() / 3, width(), 2 * height() / 3);
  drawMultiColorDashedLine(painter, line3, 10, 20, 3, { Qt::red, Qt::black, Qt::blue, Qt::magenta }, false);
}

在此处输入图像描述

GitHub 上提供了完整的工作示例


推荐阅读