Veer Bahadur Singh
Veer Bahadur Singh

Reputation: 47

positioning QGraphicsSvgItem's center on a position.

I have a created a QGraphicsSvgItem on a QGraphicsScene with size 48x48. I want to set it's center on x= 50 and y= 50 of the QGraphicsScene(By default QGraphicsScene position the top left corner of the svg item). I have inherited QGraphicsSvgItem and reimplemented its paint function and then applied a translate operation at x= -24 y = -24,But then it shows 1/4 right bottom shape of the svg item visible.

so please suggest ,how to align the center of svgitem at x=50 ,y =50

Upvotes: 2

Views: 789

Answers (2)

codeKarma
codeKarma

Reputation: 117

Need to reimplement the paint method of the QGraphicsSvgItem also

QRectF boundingRect() const
{
        return QRectF(-24,-24,48,48);
}


void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->translate(-24,-24);
    QGraphicsSvgItem::paint(painter,option,widget);
}

Upvotes: 0

TheDarkKnight
TheDarkKnight

Reputation: 27611

A QGraphicsItem has its local top left at (0,0) by default. However, if you're inheriting from QGraphicsItem, you can change it, so that (0,0) is the centre of the item.

This is handled by the boundingRect() function. If you have an item that is of height and width 50, the default bounding rect would be returning (0,0,50,50) for (x,y,w,h).

To make the local centre (0,0) override the boundingRect function to return (-25, -25, 50, 50).

QRectF boundingRect() const
{
    return QRectF(-25, -25, 50, 50);
}

Then, to centre the item in the scene at (50,50), you just need to set the item's position to that coordinate

item->setPos(50, 50);

Upvotes: 1

Related Questions