【问题标题】:Implementing mouseMoveEvent for qgraphicsObject to follow cursor为 qgraphicsObject 实现 mouseMoveEvent 以跟随光标
【发布时间】:2018-08-10 10:14:21
【问题描述】:

我有一个 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();

}

【问题讨论】:

    标签: qt qgraphicsscene qgraphicsitem qmouseevent


    【解决方案1】:

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

    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();
    }
    

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

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多