Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Qt 在QGraphicsView上绘制时绘制shift_Qt_Qgraphicsview_Qgraphicsitem_Qgraphicsscene - Fatal编程技术网

Qt 在QGraphicsView上绘制时绘制shift

Qt 在QGraphicsView上绘制时绘制shift,qt,qgraphicsview,qgraphicsitem,qgraphicsscene,Qt,Qgraphicsview,Qgraphicsitem,Qgraphicsscene,我有个问题 我有一个继承QGraphicsView的类,假设它名为g。我重新实现了mousePressEvent方法,该方法的代码是: void GraphWidget::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt::MiddleButton) createNode(event->pos().x(), event->pos().y()); update();

我有个问题

我有一个继承QGraphicsView的类,假设它名为g。我重新实现了mousePressEvent方法,该方法的代码是:

void GraphWidget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::MiddleButton)
        createNode(event->pos().x(), event->pos().y());

    update();
    QGraphicsView::mousePressEvent(event);
}
Node *GraphWidget::createNode(qreal x, qreal y, int id)
{
    Node* node = new Node(this);
    scene()->addItem(node);
    node->setPos(x, y);
    return node;
}
createNode方法的代码为:

void GraphWidget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::MiddleButton)
        createNode(event->pos().x(), event->pos().y());

    update();
    QGraphicsView::mousePressEvent(event);
}
Node *GraphWidget::createNode(qreal x, qreal y, int id)
{
    Node* node = new Node(this);
    scene()->addItem(node);
    node->setPos(x, y);
    return node;
}
我在mainwindow类中将这个类g用作中心小部件。所以它就像QGraphicsView一样工作

问题是,当我按下绘图区域上的中间按钮时-点被创建,但不在我单击的位置-点被移动。为什么?因此,当我试图通过按下中间按钮来绘制这些点时——所有这些点都被绘制在错误的位置,而不是光标下方,它们被绘制在光标位置的左侧和上方

如何解决此问题?

QGraphicsView和qgraphicscene具有不同的坐标空间。当您调用setPos时,它应该在场景坐标中,但是由于您在视图的鼠标事件中,所以您的x和y将在视图坐标中

我认为将x和y坐标映射到场景空间应该可以解决这个问题:

node->setPos( mapToScene(QPoint(x, y) );
QGraphicsView和QGraphicscene具有不同的坐标空间。当您调用setPos时,它应该在场景坐标中,但是由于您在视图的鼠标事件中,所以您的x和y将在视图坐标中

我认为将x和y坐标映射到场景空间应该可以解决这个问题:

node->setPos( mapToScene(QPoint(x, y) );

是的,问题解决了。谢谢,你的Qt真的很棒!是的,问题解决了。谢谢,你的Qt真的很棒!