0
votes

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.

1
Does your custom items return correct bounding rect ?uchar
yes, boundingRect() method of my custom items returns correct information. I added this and some other new information to the post "Edit 1".diegob
Did you override shape()? this is used for hit-detection, among other thingsking_nak
No, I didn't. Overriding shape() method, itemAt() starts to return correctly for my custom items. Thank you!diegob
Please post your solution as an answer to your own question. Answers to one's own questions are encouraged, when you figure things out.Kuba hasn't forgotten Monica

1 Answers

0
votes

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