Question

I have a problem with determining position of QGraphicsLineItem. I want to move items on the scene relatively, so I need to know their position. I have few QGraphicsPixmapItem objects and I do not have problem with them because pixmapItem.pos() gives me realistic position of every item in scene coordinates. But with QGraphicsLineItems i get the same coordinate (0,0) for every line. Here is code:

QGraphicsLineItem*line = new QGraphicsLineItem();
scene->addItem(line);
line->setLine(QLineF(0,VVR-i*(OH),HVR,VVR-i*(OH)));

This code draws lines in correct position, but its coordinates are set to (0,0) not to (0,VVR-i*(OH)).

The following code should move the line item by (VVR + OH) when it reaches position greater than VVR. But since all lines have starting position (0,0), wherever I put them, all lines are moved at the same time.

QPointF current_pos = line->pos();
if (current_pos.y() >= VVR)
{
    line->setPos(current_pos.x(),current_pos.y()-(VVR+(OH)));
}

How can I get the real (scene) coordinates of the QGraphicsLineItem, as I get for QGraphicsPixmapItem Thanks!

Was it helpful?

Solution

Each graphics item has initial position at (0, 0). You can set its new position using setPos. All its contents will be shifted according to new position.

But setLine doesn't change item position. This method change the object the item represents instead. For example, an object can be (0, 5) - (5, 5) line. If you didn't set item position, the position remains at (0, 0) and the line is shown at (0, 5) - (5, 5). If you set e.g. position (2, 0), the line will be shifted to (2, 5) - (7, 5) position. There are methods similar to setLine in other basic graphics item classes (e.g. QGraphicsPixmapItem::setOffset).

If you want to get the line position that was set previously by setLine(), use line() method. If you shifted the item using setPos(), use pos().

Additionally, since you said that you want to move items on the scene relatively, I'd like to mention the following fact. If you set a parent item for an item, its position will be calculated relatively to the parent item. You might find it useful.

OTHER TIPS

Although it's a bit strange to ask for the "line of the lineitem", I believe you want:

QPointF current_pos = line->line().p1();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top