QGraphicsItem hit detection problem.

I am having an issue where my QGraphicsItem is not alway performing proper hit detection with the mouse. I have subclassed QGrahicsItem and have overridden the shape() method. My shape() method calculates a polygon that surrounds the line. my boudingRect() function calculates a box that completely encloses the line. I have attached two screenshots. The first show the line highlighted in blue, indicating the hover event was fired. The second show the mouse moved just slightly to the right, but still well within the shape() and boundingRect() but the hover event did not fire. Any ideas on what I'm doing wrong?

I should also note that if I move the endpoints of the line, the hit detection usually starts working normally. It seems somewhat random as to when it breaks.

Note: The polygon surrounding the line is the shape() and the rectangle around that is the boundingRect()

I put the check inside the mousePress event. When the line is not hovering, it is also not recieving the mousePress event. Qt thinks that the mouse is not inside the objects shape. However, I'm still drawing the shape and it is clearly correct. :/

I think the problem is with the boundingRect(). If I understand correctly, Qt is constantly polling the boundingRect() of all of the objects. Then if the mouse is within a boundingRect(), it then polls shape() of that object.

I placed a breakpoint in shape(). It does not get called until the mouse enters the boundingRect(). When the hover is not working, the mouse is well within the boundingRect(), but shape is not called.

I recently encountered the same issue. I didn't know that the boundingRect() was used to trivially reject items, but it makes perfect sense. However, if you don't account for line thickness when computing the boundingRect, then it will have area = 0 when lines/curves are horizontal or vertical and this will cause your QGraphicsItem to be trivially rejected before shape() is hit tested.

The solution for me was to implement the shape() function to include thickness plus any additional padding if necessary to make hovering/selection easier (using QPainterPathStroker). Then the boundingRect() implementation just returns shape().boundingRect().