Solved QGraphicsItem not setting position relative to parent item?
-
Hi -
I have a custom class which inherits from QGraphicsLineItem. The reason for creating a custom class is I wanted to add text to the line at the central point of the line. The way I currently have this implemented (stripped down version) is
QPointF from(itemFrom->pos()); QPointF toPoint(itemTo->pos()); QLineF line(fromPoint, toPoint); setLine(line); label = new QGraphicsSimpleTextItem(labelText, this); QPointF labelPoint(0,0); label->setPos(labelPoint);
This however does not work, the text appears at the 0, 0 scene coordinates? I thought that when an item is in a parent-child relationship that the coordinates for the child on the label->setPos() are relative to the parent? So 0, 0 should be the center point of the parents bounding rect (i.e. the middle of the line) not the coordinates in the scene? Or am I completely wrong? I've read the documentation on the coordinates page but I still can't see where I am going wrong, perhaps it is something simple.
-
Hi,
If you want people to check your code and how it works, you need to provide a minimal compilable example that allows to reproduce the behaviour you have.
-
@Bob1
I think you may have to call the prepareGeometryChange() function when you make geometric changes. Did you do this somewhere? docs are here -
I have tried my best to illustrate what I mean, please find the source code on this GDrive link, I can't upload files here - link text.
Essentially I want the text item (part of the Link class) to be set by coordinates of the parent item which should be the line? So in this case 0,0 should be where the line begins? I've written in the comments that setting the label to line().center() does essentially what I want but isn't this using scene coordinates (which I think can be seen via the print statement below the setPos call in Link.cpp?
Any ideas where I am going wrong? Cheers!
-
@Bob1 you should set positions of your 'Link' objects since they are the parents of the 'QGraphicsSimpleTextItem' objects in your code. Setting line with 'QGraphicsLineItem::setLine' method does not change position of the 'QGraphicsLineItem' object.
Note that you will also need to change line points position calculation code (in 'Link' constructor) since line position will be relative to your 'Link' object position.
-
@casdevel Ah that was it! Many thanks, I really appreciate it.