4

I am trying to find the items under the mouse in a scene. The code I am using is as follows:

    QPainterPath mousePath;
    mousePath.addEllipse(mouseEvent -> pos(),5,5);
    QList<QGraphicsItem *> itemsCandidate = this->items(mousePath);
    if (!(itemsCandidate.contains(lastSelectedItem))) lastSelectedItem =itemsCandidate.first();

PS: this refers to a scene.

The code should find the items intersected by a small circle around the mouse position and keep the item pointer unchanged if the previous intersected one is still intersected, or take the first in the QList otherwise.

Unfortunately, this code does not work with items inside each other. For example, if I have a Rect side a Rect, the outer Rect is always intersecting the mouse position even when this one is near the inner Rect. How can i solve this?

UPDATE: This seems not to be a problem with polygons, but with Rect, Ellipses, etc.

UPDATE: This code is in the redefined scene::mouseMoveEvent

Francesco
  • 481
  • 2
  • 4
  • 16

1 Answers1

0

You can reimplement ‍mouseMoveEvent in ‍QGraphicsView‍ to capture mouse move events in view and track items near the mouse like:

void MyView::mouseMoveEvent(QMouseEvent *event)
{
    QPointF mousePoint = mapToScene(event->pos());

    qreal x = mousePoint.x();
    qreal y = mousePoint.y();

    foreach(QGraphicsItem * t , items())
    {
        int dist = qSqrt(qPow(t->pos().x()-x,2)+qPow(t->pos().y()-y,2));
        if( dist<70 )
        {
            //do whatever you like
        }
    }

    QGraphicsView::mouseMoveEvent(event);
}
Nejat
  • 31,784
  • 12
  • 106
  • 138
  • 1
    If i understand it correctly, this does not work as it uses the position of the item origin not the entire shape meaning that the nearest item so found is the one with the nearest origin not nearer edge. – Francesco Apr 06 '14 at 14:02
  • You have to implement a method to calculate the normal from mouse_position to the edges of your objects. For trivial objects like rectangles, circles, ellipses this should be quite trivial. – OnWhenReady Apr 06 '14 at 14:44
  • So there is no out if the box way. I was afraid the only choice was to use items() to select the ones intersecting in area and then calculate the distance manually per item. – Francesco Apr 06 '14 at 14:50