Qt : problem between View coordinates and View coordinates to add item

眉间皱痕 提交于 2020-06-17 13:29:52

问题


I'm struggling for 2 days with my QGraphicsScene and QGraphicsView.

When I click on the top left corner of my view (0,0), the mouse click event get the 0,0 but when I add item to the scene, it gives different coordinates and I can't find why. I think the problem is inside the scene->addItem

Here is the code :

void GraphBoard::drawState(QPoint cpoint)
{

    qDebug() << "Coordonnées QPoint dans drawState "<< cpoint;
    qDebug() << "Coordonnées QPoint dans drawState x"<< cpoint.x();
    qDebug() << "Coordonnées QPoint dans drawState y"<< cpoint.y();
    QGraphicsEllipseItem * mellipse = new QGraphicsEllipseItem(cpoint.x(),cpoint.y(),100,100);
    QPen pen;
    pen.setWidth(8);
    mellipse->setPen(pen);
    scene->addItem(mellipse);


}



void GraphBoard::mousePressEvent(QMouseEvent *event)
{
    qDebug() << "Coordonnées Mouse Press Event "<<event->pos();
    if(globalAddStateMode==true)

    {
        if (event->button() == Qt::LeftButton) {
            QPoint clickLocation=event->pos();
           drawState(clickLocation);
           globalAddStateMode=false;
        }
    }

}

The qDebug()

Coordonnées Mouse Press Event QPoint(0,1)

Coordonnées QPoint dans drawState QPoint(0,1)

Coordonnées QPoint dans drawState x 0

Coordonnées QPoint dans drawState y 1

The result on my program

The only things I did with the scene are:

 scene = new QGraphicsScene();

        QPen pen;

        //axis
        pen.setStyle(Qt::DashLine);
        scene->addLine(0,-800,0,800,pen);
        scene->addLine(-800,0,800,0,pen); //horizontal line

view->setScene(scene);
    scene->setBackgroundBrush(Qt::gray);

回答1:


Actually I quickly solved my problem with :

QPointF clickLocation=mapToScene(event->pos());

And with an offset -50, -50:

QGraphicsEllipseItem * mellipse = new QGraphicsEllipseItem(cpoint.x()-50,cpoint.y()-50,100,100);

to make the circle appear arround the mouse



来源:https://stackoverflow.com/questions/62278574/qt-problem-between-view-coordinates-and-view-coordinates-to-add-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!