Reputation:
My class inherits from QGraphicsItem. I draw it with painter->drawArc, and I want to make the same bound for that object, but QpainterPath does not have such function as painter. arcTo it is not the same, because it has line from center.
Code (Width is a width of pen, so the collision is on the external border of arc.):
QRectF Circle::boundingRect() const
{
QRectF rect( -radius, -radius, radius*2, radius*2);
return rect;
}
QPainterPath Circle::shape() const
{
QPainterPath path;
path.arcTo(-radius-width, -radius-width, (radius+width)*2, (radius+width)*2, startAngle/16, spanAngle/16);
return path;
}
void Circle::paint(QPainter * painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QPen pen;
pen.setCapStyle(Qt::FlatCap);
pen.setWidth(width);
painter->setPen(pen);
painter->drawArc(boundingRect(), startAngle, spanAngle);
}
Upvotes: 0
Views: 1054
Reputation: 2602
You have to use QPainterPath::arcTo
, but you have to move the current position in the start point of the arc, otherwise the arc will be connected to the current position with a line.
To move the current position in the start point, you can use QPainterPath::arcMoveTo
Example
QPainterPath pp;
pp.arcMoveTo(rect, startAngle);
pp.arcTo(rect, startAngle, spanAngle);
Consider also to use QPainterPathStroker
to give a thickness to the shape. And also add the pen width to the bounding rect
Example:
QRectF Circle::boundingRect() const
{
return QRectF(-radius - width, -radius - width, (radius + width) * 2, (radius + width) * 2);
}
QPainterPath Circle::shape() const
{
QRectF rect(-radius, -radius, radius * 2, radius * 2);
QPainterPath path;
path.arcMoveTo(rect, startAngle / 16);
path.arcTo(rect, startAngle / 16, spanAngle / 16);
QPainterPathStroker pps;
pps.setCapStyle(Qt::FlatCap);
pps.setWidth(width);
return pps.makeStroke(path);
}
void Circle::paint(QPainter * painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QPen pen;
pen.setCapStyle(Qt::FlatCap);
pen.setWidth(width);
painter->setPen(pen);
QRectF rect(-radius, -radius, radius * 2, radius * 2);
painter->drawArc(rect, startAngle, spanAngle);
}
Upvotes: 1