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

主宰稳场 提交于 2019-12-22 11:26:15

问题


I have a class inheriting from QGraphicsLineItem and as soon as I override the paint method, it looks like Qt starts painting it at every "main loop", instead of drawing according to some events (like moving the item, etc).

Does anyone know more about the good practices when inheriting from a QGraphicsItem ? I look at other projets' code and it looks like it does not come from my paint method. I was thinking that maybe I'm doing something wrong in the paint method that changes the items states to "to be painted again", and so Qt paints it again. I joined the method code in case of. The method paints an arrow.

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);
}

Thank you for your help !


回答1:


You probably shouldn't call methods like setPos, setRect, setPolygon or update inside your paint() method. These methods are likely to schedule a new paint event which will lead to infinite recursion.



来源:https://stackoverflow.com/questions/6246158/100-cpu-usage-when-overriding-qgraphicslineitempaint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!