我有一个继承自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);
}
感谢您的帮助!