Search code examples
qtqgraphicsview

Can't draw new item on QGraphicsScene exactly under mouse cursor


I have such code to draw new vertex under mouse cursor.

void DiaScene::mouseReleaseEvent(QGraphicsSceneMouseEvent * me)
{

qDebug() << Q_FUNC_INFO << me->scenePos();
if (this->cursorState == VERTEX)
{
    Vertex * v = new Vertex(1,1);
    vertexes.append(v);
    this->addItem(v);
    qDebug() << me->pos();
    v->setPos(me->scenePos());
    qDebug() << me->scenePos();
}

}

When running, I click multiple times on the same place, but qdebug shows different QPointF, and draws new item not under cursor. I understand why me->ScenePos() changes. But why scene does not draw new vertex under cursor?

Firstly it draws new item some far from cursor. With every next click on the same place the position of newly drawed item becomes closer to cursor.


Solution

  • "With every next click on the same place the position of newly drawed item becomes closer to cursor"

    This behaviour means that your scene doesn't have a fixed size and its SceneRect grows with every new added item. You will see this if you add a folllowing line qDebug()<<sceneRect(); in the end of a mouseReleaseEvent handler. To fix it simply set scene rect to a parent's GraphicsView rect:

    QRect r = QRect(0,0, ui->graphicsView->width(), ui->graphicsView->height());
    MyScene* sc = new MyScene();
    ui->graphicsView->setScene(sc);
    sc->setSceneRect(r);