Centering an Item in a QGraphicsView



  • The following code doesn't center the item, selected from the QGraphicsScene items list, in the view as expected:

    @
    class GraphicsMapView : public QGraphicsView
    {
    Q_OBJECT

    public:
    GraphicsMapView(QGraphicsView *parent = 0);
    ~GraphicsMapView();
    void updateView(QPointF& pos);

    private:
    QGraphicsScene scene;

    };

    void GraphicsMapView::updateView(QPointF& pos)
    {
    QGraphicsEllipseItem* item1 = dynamic_cast<QGraphicsEllipseItem*>(scene.items()[1]);
    item1->setPos(pos);

    QRectF sceneRect(pos.x(),
                     pos.y(),
                     width(),
                     height());
    
    setSceneRect(sceneRect);
    

    }@

    The item is visible in the view but not centered and I can't achieve to center it in the view.



  • I've finally found a solution which seems to work fine, if this can help somebody:

    @
    item1->setPos(pos);
    setSceneRect(item1->sceneBoundingRect());
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.