Search code examples
c++qtqgraphicsviewqgraphicsitemqgraphicsscene

Access other item contents within a QGraphicsScene


I have a dialog.cpp file, it is within here I created my QGraphicsScene which uses the QGraphicsView.

I created two classes that inherit QGraphicsPixmapItem, "Vehicle" and "Junction". Both of these objects are added to the same QGraphicsScene in my dialog.cpp file.

I want to call a method which is a member of "Junction" from my "Vehicle" object. The method returns a boolean value which I need.

This is more of a c++ orientated question, as I'm sure there's an easy solution which makes use of accessing a parent.

Background info on project: Each "Vehicle" moves along a road and approaches a "Junction". The vehicle must then ask the junction "does my lane have a green light to go?", the junction will then reply "true/false".


Solution

  • After reviewing possible solutions via the QT documentation I have partly resolved the issue.

    Calling this->scene() allows access to member functions of the scene, on which your object was added. Since I know the co-ordinates of my object I call, this->scene()->itemAt(240,0); to retrieve a pointer to the item.

    The pointer returned is the uppermost item on the scene at the co-ordinates supplied. If this provides a problem alternately use scene()->items() to retrieve a list of all the items on the scene.

    However, this only gives access to the item and not the vector in which the item is stored. I have been looking into using the ->parent() function and think this may be the solution, combined with dynamically casting it to the required pointer. Will update the answer if I find a full solution.