【问题标题】:100% CPU usage when overriding QGraphicsLineItem::paint()覆盖 QGraphicsLineItem::paint() 时 100% CPU 使用率
【发布时间】:2011-06-06 08:25:18
【问题描述】:

我有一个继承自 QGraphicsLineItem 的类,一旦我重写了 paint 方法,看起来 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);
}

感谢您的帮助!

【问题讨论】:

    标签: c++ qt qt4


    【解决方案1】:

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

    【讨论】:

    • 这是来自 update(),我刚刚删除了那行,现在可以了。谢谢。
    猜你喜欢
    • 2012-12-05
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多