You are not logged in.

Dear visitor, welcome to QtForum.org. If this is your first visit here, please read the Help. It explains in detail how this page works. To use all features of this page, you should consider registering. Please use the registration form, to register here or read more information about the registration process. If you are already registered, please login here.

1

Monday, October 18th 2010, 4:02am

Get the qgraphicsitem under the mouse

Hi all,

I'm trying to use the mouse to move a qgraphicsitem (rectangle) in my scene. However, no matter what I do, the left click event doesn't seem to be received by the qgraphicsscene. Is there a way to determine what object is underneath the mouse, when it is clicked?

Doug

2

Monday, October 18th 2010, 8:47am

Hi,

Your item must have some flags in order to move it in the scene for example:

Source code

1
2
item->setFlag(QGraphicsItem::ItemIsMovable, true);
item->setFlag(QGraphicsItem::ItemIsSelectable, true);


to determine what object is underneath the mouse, you need to subclass the scene and reimplement the mousePressEvent, for example:

Source code

1
2
3
4
5
6
7
8
9
10
11
void myscene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
  QGraphicsScene::mousePressEvent(mouseEvent); //Call the ancestor
  
  QGraphicsItem *item;
   item = itemAt(mouseEvent->scenePos()); //Get the item at the position
   if (item) //If there is an item at that position
   {
     //Some code
   }
}