QGraphicsPathItem:以不同方式绘制元素

QGraphicsPathItem: paint elements differently

如何绘制 QGraphicsPathItem 使其在最后 n 个元素后淡出?

每一秒我都会在路径末尾添加一个QPointF,并希望以100% 的不透明度显示第n 个元素。 n-1 占 90%,n-2 占 80% 等。所以路径只显示最后 10 个(例如)并平滑淡出。但是我怎样才能用 qt5 做到这一点呢?

我想出了如何更改整个路径的颜色,但我如何在子项目级别更改它...这里指的是路径元素?

它是关于重新实现 QGraphicsPathItem::paint() 方法(如 Kuba 提到的)并使用 QBrushQLinearGradient 逐段绘制路径。

如果需要,我可以更具体。

我会为每个部分使用单独的 QGraphicsLineItem 并独立调整它们的不透明度:

class Object : public QObject {
  Q_OBJECT
public:
  Object();
  void add_point(QPointF point);
private:
  QGraphicsScene m_scene;
  QList<QGraphicsLineItem*> m_items;
  QPointF m_previous_point;
private slots:
  void timeout();
};

Object::Object() {
  QGraphicsView* view = new QGraphicsView();
  view->setRenderHint(QPainter::Antialiasing);
  view->setScene(&m_scene);
  view->scale(10, 10);
  view->resize(400, 200);
  view->show();
  QTimer* timer = new QTimer(this);
  timer->start(30);
  connect(timer, &QTimer::timeout, this, &Object::timeout);
}

void Object::add_point(QPointF point) {
  const int MAX_SEGMENTS = 100;
  QGraphicsLineItem* new_line = 
      m_scene.addLine(QLineF(m_previous_point, point));
  QPen pen;
  pen.setCosmetic(true);
  pen.setWidth(3);
  new_line->setPen(pen);
  m_items.append(new_line);
  while(m_items.count() > MAX_SEGMENTS) {
    delete m_items[0];
    m_items.removeFirst();
  }
  for(int i = 0; i < m_items.count(); i++) {
    m_items[i]->setOpacity(
        1.0 - 1.0 / MAX_SEGMENTS * (m_items.count() - 1 - i));
  }
  m_previous_point = point;
}

void Object::timeout() {
  double x = m_previous_point.x() + 0.1;
  add_point(QPointF(x, qSin(x)));
}