【问题标题】:Draw shift when drawing on QGraphicsView在 QGraphicsView 上绘图时绘制 shift
【发布时间】:2012-10-19 05:19:14
【问题描述】:

我有问题。

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

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

    update();
    QGraphicsView::mousePressEvent(event);
}

createNode方法的代码是:

Node *GraphWidget::createNode(qreal x, qreal y, int id)
{
    Node* node = new Node(this);
    scene()->addItem(node);
    node->setPos(x, y);
    return node;
}

我在我的主窗口类中使用这个类“g”作为中心小部件。所以它就像 QGraphicsView 一样工作。

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

我该如何解决这个问题?

【问题讨论】:

    标签: qt qgraphicsview qgraphicsitem qgraphicsscene


    【解决方案1】:

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

    我怀疑将您的 x 和 y 坐标映射到场景空间应该可以解决问题:

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

    【讨论】:

    • 是的,它解决了问题。谢谢,你真的很擅长 Qt!
    猜你喜欢
    • 1970-01-01
    • 2018-09-16
    • 2017-04-23
    • 2021-01-16
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多