使用鼠标悬停移动QGraphicsItem

时间:2013-11-19 11:02:55

标签: qt draggable

我正在尝试将鼠标悬停在父项上移动QGraphicsItem

BaseItem::BaseItem(const QRectF &bounds) 
    : theBounds(bounds), theMousePressed(false) 
{
   theLineItem = new LineItem(theBounds, this);
    setAcceptHoverEvents(true); 
}

void BaseItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) 
{
    QPointF position =  mapToScene( event->pos());
    theLineItem->setPos( position); 
}

但物品没有移动。有没有其他方法可以在不使用ItemIsMovable标志的情况下使用鼠标移动来移动场景中的项目,因为我希望项目在调用父项目后移动?

1 个答案:

答案 0 :(得分:1)

创建LineItem时,在其构造函数中将BaseItem作为父项传递。

在GraphicsItem上调用setPos,设置项目相对于其父项的位置,在这种情况下,它是BaseItem。

将event-> pos()映射到场景坐标是错误的。 event-> pos()返回接收对象的本地坐标中的位置,在本例中是BaseItem。

因此,您应该使用event-> pos()直接设置theLineItem的位置。

theLineItem->setPos(event->pos());

请注意,如果您确实想要在场景坐标中使用事件位置,那么已经有了一个功能: -

event->scenePos();

所以你不需要调用mapToScene。

相关问题