重写QGraphicsLineItem::paint()时100%的CPU使用率

100% CPU usage when overriding QGraphicsLineItem::paint()

本文关键字:100% CPU 使用率 QGraphicsLineItem paint 重写      更新时间:2023-10-16

我有一个继承自QGraphicsLineItem的类,一旦我覆盖了绘制方法,看起来Qt就开始在每个"主循环"绘制它,而不是根据一些事件进行绘制(如移动项目等)。

有人知道更多关于从QGraphicsItem继承时的良好实践吗?我看了其他项目的代码,它看起来并不是来自我的绘画方法。我在想,也许我在绘画方法上做错了什么,把物品的状态改为"再次绘画",所以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);
}

谢谢你的帮助!

您可能不应该在paint()方法中调用setPossetRectsetPolygonupdate等方法。这些方法可能会安排一个新的绘制事件,这将导致无限递归。