Search code examples
qtqt4

x,y point shifts when the width is reduced below 200 in QGraphicsScene


I have created a QGraphicsScene

scene = new QGraphicsScene(0,0,200,200);

and draw a line scene.addLine(0,0,100,100,pen); and I got the line correctly drawn from (0,0) to (100,100).

When I change the code to

scene = new QGraphicsScene(0,0,150,200);

And draw the same line scene.addLine(0,0,100,100,pen);, Its x,y point shifts to the right side by 50 pixels. Why does this happen? How to avoid this?


Solution

  • By default, the scene rectangle is centered in the QGraphicsView when it is smaller than the view.

    You can use QGraphicsView::setAlignment to change that.


    Since the view preferred size, returned by QGraphicsView::sizeHint() is also the scene size, you can adjust the view to fit exactly the scene with:

    view->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    

    which tells the layout to only use sizeHint() to calculate the size of the widget.
    Or if the view is not inside a layout, you'll have to set the size with

    view->setFixedSize(view->sizeHint()); 
    

    each time you change the scene rect size.