January 14, 2012

ksiedzulek ksiedzulek
Lab Rat
8 posts

position in scene coordinates

 

Hi,

I am learning about graphic view, I have written simple code to check how it behave and I don’t know how to get position of items in scene coordinates:/

  1. Widget::Widget(QWidget *parent) :
  2.     QWidget(parent),
  3.     ui(new Ui::Widget)
  4. {
  5.     ui->setupUi(this);
  6.     scene = new QGraphicsScene(-200,-200,400,400);
  7.     ui->graphicsView->setScene(scene);
  8.     QBrush redBrush(Qt::red);
  9.     QBrush blueBrush(Qt::blue);
  10.     QPen blackpen(Qt::black);
  11.     blackpen.setWidth(6);
  12.     rec=scene->addRect(175,-25,50,50,blackpen,blueBrush);
  13.     scene->addRect(-225,-25,50,50,blackpen,blueBrush);
  14.     scene->addRect(-25,175,50,50,blackpen,blueBrush);
  15.     scene->addRect(-25,-225,50,50,blackpen,blueBrush);
  16.  
  17.     ellipse=scene->addEllipse(-50,-50,100,100,blackpen,redBrush);
  18.     rec->setFlag(QGraphicsItem::ItemIsMovable);
  19.  
  20.     qDebug()<<ellipse->scenePos();
  21.     qDebug()<<ellipse->pos();
  22.  
  23. }

Qt documentation says about pos():

.., If the item has no parent, its position is given in scene coordinates.
The position of the item describes its origin (local coordinate (0, 0)) in parent coordinates; this function returns the same as mapToParent(0, 0).
For convenience, you can also call scenePos() to determine the item’s position in scene coordinates,..

but qDebug shows for both (pos and scenePos) “QPointF(0, 0)” I suppose its point from local scene.

3 replies

February 16, 2012

Mr-Merlin Mr-Merlin
Lab Rat
19 posts

Hi,

When you add the rects with addRect you are defining the size of each rect, but not the position.

The pos() function will give a position relative to the item’s parent, which in the case of your code is the scene, so they’re the same.

If you create two rects A and B and make B a child of A, then add rect A to the scene, you can move B and see that the functions pos() and scenePos() are different.

Hope that helps ;O)

February 16, 2012

ksiedzulek ksiedzulek
Lab Rat
8 posts

ok, i’ll check this:). it sounds good.

February 16, 2012

shoyeb shoyeb
Lab Rat
87 posts

also one thing to point out, u should not do all of your stuff in the constructor of your class….,

 Signature 

There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code.

 
  ‹‹ QLabel doesn’t get transparent background and editable text even so i did set the right flags      QSlider is not sliding ››

You must log in to post a reply. Not a member yet? Register here!