Adds QGraphicsItem to QGraphicsscene at few pixels away



  • I was trying to develop a simulator which would let you draw lines(QGraphicsLineItem) as per your mouse movement. I have registered for "mouseMoveEvent" on GraphicsView and capturing event->pos() coordinates and drawing a line of given length from that point. My code flow is as follows.

    QGraphicsScene *scene = new QGraphicsScene;
    QGraphicsView *view = new QGraphicsView;
    view->setScene(scene);
    scene->setSceneRect(geometry().x(), geometry().y(), geometry().width(), geometry().height());

    If I print the coordinates of view and scene
    qDebug()<<geometry().x(), geometry().y();
    for scene
    qdebug()<<this->sceneRect().x()<<this->sceneRect().y();

    I get 0,0 as result for both.
    On mouseMoveEvent()
    scene->addLine(event->pos()).x(), event->pos()).y(), event->pos()).x()+len, event->pos()).y());

    While I do this, I see line gets drawn at 30 pixels away from top left corner. How could I make line draw from (0,0).
    Any help is appreciated.



  • Without trying to understand the details of your code, I think what you are missing is some mapping of the event coordinates to item/view/scene coordinates. If you haven't already read about "The Graphics View Coordinate System":http://developer.qt.nokia.com/doc/qt-4.8/graphicsview.html#the-graphics-view-coordinate-system, I would suggest you do so. The answer to your question is most probably answered there.



  • Thanks ludde for your reply. The documentation you refer to me says, if at all I wish to transform view coordinates to scene coordinates, I must be using mapToScene().

    But the issue I was running into was, I was listening to mousePressEvent(QMouseEvent) of QGraphicsView and was performing painter.drawLine() of length 10 from (event->x(), event-->y()). As this doesn't get added into QGraphicsScene, I wish to add the line into QGraphicsScene. Rather doing painter.drawLine(), I wish to do addLineItem() so that I dont have to bother about zooming operations at later point of time. So, before doing addLineItem(), I have created a lineitem from new coordinates (derived out of mapToScene() ) of desired length. But I see that, the lineitem on scene gets painted pixels away rather at (event->x(), event-->y()) which I intended to happen. I would like to know the way how to achieve this. If im able to paint a line from any coordinates in view, why do we have some lateral displacement when I draw line from coordinates that I get from mapToScene() ?



  • I think you should write a minimal working example. mapToScene works fine for me. Maybe you should setup you view scene rect...



  • I have tried writing minimal example and it just works fine. I shall debug my main stream code. Thanks for all your replies.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.