2

I have a Qt application with objects derived from QGraphicsObjcet that need to be movable in a scene. I know that I can use the flags for movement to achieve this.

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

but I am having an issue with the objects popping out of position when i use it. The only time when the objects move into an incorrect position is when an object I've moved is deleted and removed from the scene, the next time I try to move another object in the scene, its position relative to mouse Cursor is distorted until I release it and press it again. I realise that my problem could be occuring somewhere completely elsewhere in my code but from my own debugging I would at least want to try and implement the move functionality myself to solve this issue.

So my question is: How can you implement movable objects (derived from QGraphicsObject) that act as if the flags above are active?

I've been trying to use mouseMoveEvent but can't figure out how I get the objects to move with the cursor. Maybe I should look into DragMoveEvent instead? If possible, I would however really appreciate to see what the code for mouseMoveEvent below would look:

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

QGraphicsObject::mouseMoveEvent(event);

update();

}
Blink
  • 163
  • 1
  • 6

1 Answers1

0

I think something like this should do the trick (not tested):

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

With the code above, your object is going to follow the mouse untill the end of the world, so you probably want to combine it with a start/stop flag. And if your item has a parent, you are probably going to need to translate the coordinates.

Andéol Evain
  • 507
  • 2
  • 12