【问题标题】:Can I use a QPainter to draw a line with a per-vertex color?我可以使用 QPainter 绘制具有每个顶点颜色的线吗?
【发布时间】:2018-02-14 19:08:21
【问题描述】:

我有一个自定义的 Qt 5 小部件,它使用 QPainter 呈现自己。我希望能够绘制一条线,其中每个顶点都与不同的颜色相关联,并且颜色会沿着连接点的线进行相应的插值。这可能吗?

【问题讨论】:

    标签: qt5 qpainter


    【解决方案1】:

    我认为您需要逐行绘制。假设这是可以接受的,那么使用合适的 QLinearGradient 初始化的 QPen 应该可以工作...

    class widget: public QWidget {
      using super = QWidget;
    public:
      explicit widget (QWidget *parent = nullptr)
        : super(parent)
        {
        }
    protected:
      virtual void paintEvent (QPaintEvent *event) override
        {
          super::paintEvent(event);
          QPainter painter(this);
    
          /*
           * Define the corners of a rectangle lying 10 pixels inside
           * the current bounding rect.
           */
          int left = 10, right = width() - 10;
          int top = 10, bottom = height() - 10;
          QPoint top_left(left, top);
          QPoint top_right(right, top);
          QPoint bottom_right(right, bottom);
          QPoint bottom_left(left, bottom);
    
          /*
           * Insert the points along with their required colours into
           * a suitable container.
           */
          QVector<QPair<QPoint, QColor>> points;
          points << qMakePair(top_left, Qt::red);
          points << qMakePair(top_right, Qt::green);
          points << qMakePair(bottom_right, Qt::blue);
          points << qMakePair(bottom_left, Qt::black);
          for (int i = 0; i < points.size(); ++i) {
            int e = (i + 1) % points.size();
    
            /*
             * Create a suitable linear gradient based on the colours
             * required for vertices indexed by i and e.
             */
            QLinearGradient gradient;
            gradient.setColorAt(0, points[i].second);
            gradient.setColorAt(1, points[e].second);
            gradient.setStart(points[i].first);
            gradient.setFinalStop(points[e].first);
    
            /*
             * Set the pen and draw the line.
             */
            painter.setPen(QPen(QBrush(gradient), 10.0f));
            painter.drawLine(points[i].first, points[e].first);
          }
        }
    };
    

    上面的结果类似于...

    (注意:使用QPainterPathQPainterPathStroker 可能有更好的方法来实现这一点,但我不确定是否基于文档。我已经看过了。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      • 2022-10-01
      • 1970-01-01
      • 2020-01-14
      • 2018-06-27
      • 2015-12-25
      • 2012-10-19
      相关资源
      最近更新 更多