View Full Version : GraphicsItem Question

12th May 2009, 18:02
I have a GraphicsScene with a bunch of GraphicsItems that can be dragged around in the scene.

This is what I want to do....

Suppose I click the GrahicsItem and drag it to a new location...right when i RELEASE the mouse's left click(to drop it)...I want to run a function..

(In case you were curious of my project..it is a chess project..I want to run the function to center the pieces every time I release the mouse click.)


12th May 2009, 19:48
You can override the drag drop mechanism.
ie. starg drag on mouse press / mouse event, move the item whil dragging, and finally on mouse release check the position of item, and adjust accordingly.

13th May 2009, 06:02
I thought this would only work on widgets....

How would I do this for a graphicsItem?

13th May 2009, 06:33
Well actually you can do it in Scene.
I had previously done similar thing. I had to move back item if it was dropped in areas not allowed, or align the item to cell if it was dropped somewhere in middle.

I will brief abt my implementation :

1) In scene::mousePressEvent capture the position of mouse press. Check if item lies underneath it.

2) You can start drag on mousepress or mouse move, mouse move is advisable, after the user has picked item and tried to move it.
To start drag, see QDrag. You will need to populate mime data for it.

3) Now in drag move event, move the item that started the drag along with the mouse cursor ( You will need to store item pointer in scene which is under drag..

4) On scene::dropEvent, check the position of item, and do ur calculations.

Hope this helps :)

13th May 2009, 09:02

You can do this in the following way,

1. first you should set the ItemIsMovable flag


2. then you gotta reimplement itemChange method.

13th May 2009, 11:24
Hi guys, what about the


event ???
This is exactly what you need!

13th May 2009, 12:13
QGraphicsItem::itemChange is also a good option.
But in this case the item will need to know where it can be placed in the scene.

Its more appropriate that a higher level ( scene ) decides what items will be placed where.

Rest , design issue,,, u can choose which suits you.

14th May 2009, 18:40
Sorry..if this question is too basic

but..I did re implement the QGrahpicsScene

what I have below isn't working

class scene: public QGraphicsScene


void mouseReleaseEvent(QMouseEvent *event)


Everytime I drag a graphicsitem from one place to another and release the mouse button..the scene doesn't clear...

Please help

14th May 2009, 21:11
That's because your method is never called. mouseReleaseEvent() in the scene takes a QGraphicsSceneMouseEvent pointer.