2014-09-29 74 views
1

我有一個QGraphicsScene創建一個大小爲48x48的QGraphicsSvgItem。 我想將它設置在QGraphicsScene的x = 50和y = 50的中心(默認情況下,QGraphicsScene位於svg項目的左上角)。 我已經繼承了QGraphicsSvgItem並重新實現了它的繪製函數,然後在x = -24 y = -24處應用了一個平移操作,但是它顯示了可見的svg項的1/4右下形狀。將QGraphicsSvgItem的中心定位在某個位置上。

所以請建議,如何使svgitem中心在x = 50,y = 50

回答

1

一個的QGraphicsItem在默認情況下,在(0,0)離開本地頂部。但是,如果您從QGraphicsItem繼承,則可以更改它,以便(0,0)是該項目的中心。

這是由boundingRect()函數處理的。如果您的項目高度和寬度爲50,則(x,y,w,h)的默認邊界矩形將返回(0,0,50,50)。

使本地中心(0,0)覆蓋boundingRect函數以返回(-25,-25,50,50)。

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

然後,居中項目在場景中(50,50),你只需要設置的項目的該位置座標

item->setPos(50, 50); 
0

需要重新實現QGraphicsSvgItem將的paint方法也

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