首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用QPen的带有虚线图案的多色虚线

使用QPen的带有虚线图案的多色虚线
EN

Stack Overflow用户
提问于 2019-07-31 17:56:40
回答 1查看 1.9K关注 0票数 1

我需要用QPen画一条五颜六色的线,它可能由虚线图案中的三种颜色组成。

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

对我如何做到这一点有什么建议吗?

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-01 09:00:35

开发@goug的想法,您可以这样做:

代码语言:javascript
复制
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对每种颜色进行移动:

代码语言:javascript
复制
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);
  }
}

因此,它们可以被称为:

代码语言:javascript
复制
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上使用。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57296497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档