我有一个问题。
我有一个继承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类似。
问题是,当我按下“绘图区域”中的中间按钮时 - 创建点但不是在我点击的位置 - 点被移动。为什么?因此,当我尝试通过按下中间按钮来绘制这些点时 - 所有这些点都绘制在错误的位置(不在我的光标下,它们是在左侧和上方光标位置之后绘制的)。
我该如何解决?
答案 0 :(得分:4)
QGraphicsView
和QGraphicsScene
具有不同的坐标空间。当你调用setPos
时,它应该在场景坐标中,但由于你在视图的鼠标事件中,你的x和y将在视图坐标中。
我怀疑将x和y坐标映射到场景空间应该可以解决问题:
node->setPos( mapToScene(QPoint(x, y) );