当覆盖QGraphicsLineItem::paint()方法时,CPU使用率达到100%

3

我有一个继承自QGraphicsLineItem的类,当我重写paint方法时,Qt似乎会在每个“主循环”中开始绘制它,而不是根据某些事件(如移动项等)进行绘制。

有人知道从QGraphicsItem继承时的最佳实践吗?我查看了其他项目的代码,似乎并不是来自我的paint方法。我想也许我在paint方法中做错了什么,导致项的状态变为“需要重新绘制”,因此Qt会再次绘制它。我附上了方法代码以防万一。该方法绘制了一个箭头。

void Message::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
  QLineF line = this->line();
  Instance* from = dynamic_cast<Instance*> (this->from_get());
  Instance* to = dynamic_cast<Instance*> (this->to_get());

  QPointF from_pt(from->x() + from_pos_.x(), from->y() + from_pos_.y());
  line.setP1(from_pt);
  this->setLine(line);

  QPointF to_pt(to->x() + to_pos_.x(), to->y() + to_pos_.y());
  line.setP2(to_pt);
  this->setLine(line);

  textItem_->setPos(this->boundingRect().center().x() - textItem_->boundingRect().width() / 2,
                    this->boundingRect().center().y() - textItem_->boundingRect().height() / 2);
  rectItem_->setRect(textItem_->x(), textItem_->y(), textItem_->boundingRect().width(), textItem_->boundingRect().height());

  if (this->line().dy() >= 0)
  {
    int arrowSize = 14;
    double angle = ::acos(this->line().dx() / this->line().length());
    QPointF arrowP1;
    QPointF arrowP2;
    QPolygonF p;

    angle = (Pi * 2) - angle;
    arrowP1 = this->line().p2() - QPointF(sin(angle + Pi / 3) * arrowSize, cos(angle + Pi / 3) * arrowSize);
    arrowP2 = this->line().p2() - QPointF(sin(angle + Pi - Pi / 3) * arrowSize, cos(angle + Pi - Pi / 3) * arrowSize);
    p << this->line().p2() << arrowP1 << arrowP2;
    extremity_->setPolygon(p);
    extremity_->update(extremity_->boundingRect());
  }

  extremity_->paint(painter, option, widget);

  QGraphicsLineItem::paint(painter, option, widget);
}

感谢您的帮助!
1个回答

4

paint()方法内部,您可能不应该调用像setPossetRectsetPolygonupdate这样的方法。这些方法很可能会安排一个新的绘画事件,导致无限递归。


那是来自update()的,我只是删除了那一行,现在没问题了。谢谢。 - Julio Guerra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接