PDA

View Full Version : Drawing lines using QGraphicsLineItem and setting its position



fusion44
20th April 2014, 19:35
Hi All,

I'm trying to follow this tutorial: http://www.informit.com/articles/article.aspx?p=1174421&seqNum=4
Works pretty well until the point when I try to draw a line between my two rectangles. The position from my two nodes seem to be off.
I've recorded a video to explain the problem a little better ( Sorry for the video quality :/ ) :


https://www.youtube.com/watch?v=j4f2n_TeZZM
Selecting 480p makes the text somewhat readable. The rectangle is always showing the current position in the scene, which is the same that is used to set the lines position.

Here's the code for setting the line:

void Link::trackNodes()
{
setLine(QLineF(myFromNode->pos(), myToNode->pos()));
}

And here's how I setup the scene:

//Set-up the scene
QGraphicsScene* scene = new QGraphicsScene(this);
//Set-up the view

QGraphicsRectItem *scene_rect_item = new QGraphicsRectItem();
QRectF scene_rect(0,0, 300, 300);
scene_rect_item->setRect(scene_rect);
setSceneRect(scene_rect);
scene->addItem(scene_rect_item);

setDragMode(QGraphicsView::RubberBandDrag);
setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
setContextMenuPolicy(Qt::ActionsContextMenu);

setScene(scene);

Any ideas what might cause this?

Thank you in advance!

fusion44
27th April 2014, 17:12
If somebody has the same problem, this is how I've solved it:


QPointF pf = mapToItem(mFromNode, pos());
QPointF pt = mapToItem(mToNode, pos());
setLine(pf.x(), pf.y(), -pt.x(), -pt.y());


If you map the items to its parent, it should work. Its not clearly obvious to my why this is, especially that I have to negate the second position.
I couldn't find an explanation for this behavior in the docs. Seems like the parent / child relationship works in a different way that I'm used to.

snitchjinx
15th July 2019, 16:39
Thanks! Your post has saved my day!:)


If somebody has the same problem, this is how I've solved it:


QPointF pf = mapToItem(mFromNode, pos());
QPointF pt = mapToItem(mToNode, pos());
setLine(pf.x(), pf.y(), -pt.x(), -pt.y());


If you map the items to its parent, it should work. Its not clearly obvious to my why this is, especially that I have to negate the second position.
I couldn't find an explanation for this behavior in the docs. Seems like the parent / child relationship works in a different way that I'm used to.