0

I have some custom QGraphicsItems in a QGraphicsView of a QGraphicsScene.
I wish to know if there is an Item in the view at given (x,y) coordinates.

To test purpose I use the following class as QGraphicsScene:

class CustomScene : public QGraphicsScene
{
protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event)
    {
        if (QGraphicsItem *item = itemAt(event->scenePos())) {
            qDebug() << "You clicked on item" << item;
        } 
        else {
            qDebug() << "You didn't click on an item.";
        }
    }
};  

In my application I have:

  • a class "Screen::Screen(QWidget *parent): QWidget(parent){...}" with inside an instance of my class "CustomScene : public QGraphicsScene {...}" described above and an instance of class QGraphicsView.
  • some instances of my class "Rect : public QGraphicsRectItem {...}", added to the QGraphicsView,s that draw some rectangles after some calculations.

When I launch the application and click on the drawn rectangles, I always have "You didn't click on an item." message.

Searching here in previous posts or searching on google I didn't find the reason why my code doesn't work. What am I doing wrong?

Edit 1: boundingRect() method returns correctly. I tried to add some QGraphicsRectItem, itemAt() method returns their information correctly.

diegob
  • 35
  • 6

1 Answers1

0

The problem was that I didn't override the QPainterPath QGraphicsItem::shape () const [virtual] method.
Once done, itemAt() method started to works as expected.

diegob
  • 35
  • 6
  • That shouldn't be neccessary, because the default implementation returns a `QPainterPath` of the `boundingRect()`. The problem must be somewhere else. Can you please add your implementation of `shape()` to your answer? – Martin Hennings Jun 19 '18 at 08:04