2

我有一个 Qt 应用程序,其中包含从 QGraphicsObjcet 派生的对象,这些对象需要在场景中移动。我知道我可以使用移动标志来实现这一点。

myObject->setFlag(QGraphicsItem::ItemIsMovable); myObject->setFlag(QGraphicsItem::ItemIsSelectable); myObject->setFlag(QGraphicsItem::ItemSendsGeometryChanges);

但是当我使用它时,我遇到了对象弹出位置的问题。对象移动到不正确位置的唯一时间是当我移动的对象被删除并从场景中移除时,下次我尝试移动场景中的另一个对象时,它相对于鼠标光标的位置会失真,直到我松开并再次按下。我意识到我的问题可能完全发生在我的代码的其他地方,但从我自己的调试来看,我至少想自己尝试实现移动功能来解决这个问题。

所以我的问题是:如何实现可移动对象(从 QGraphicsObject 派生),就像上面的标志处于活动状态一样?

我一直在尝试使用 mouseMoveEvent,但不知道如何让对象随光标移动。也许我应该研究 DragMoveEvent ?如果可能的话,我真的很感激看到下面 mouseMoveEvent 的代码会是什么样子:

void myObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
// How do I get myObject to follow 
// the event pos in the scene from here?

QGraphicsObject::mouseMoveEvent(event);

update();

}
4

1 回答 1

0

我认为这样的事情应该可以解决问题(未经测试):

void myObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{

// Set the item position as the mouse position.
this->setPos(event->scenePos());
// If your object (this) has no parent, then setPos() place it using scene coordinates, which is what you need here.

QGraphicsObject::mouseMoveEvent(event);
update();
}

使用上面的代码,您的对象将跟随鼠标直到世界末日,因此您可能希望将它与开始/停止标志结合起来。如果您的项目有父项,您可能需要翻译坐标。

于 2018-03-02T15:36:51.810 回答