Search code examples
c++qtqt5qgraphicsviewqgraphicsitem

How to insert pointer in QGraphicsItem so when they get selected pointer will be accessed?


I want to select rectangle/polyline through scene with mouse click and should be able to print it's name and other property. It's name and other properties are in the graph node. But I dont want to interact graph again.

So when I was drawing rectangle/polyline through graph co-ordinates, I should be able to store some pointer of graph node on rectangle/polyline so when I will click on rectangle/polyline, then through that pointer I can access it's name and other properties.

Question is `Is this possible ?

Among all above parameters, I want to store only _Ptr ( it is basically a pointer, but store as long, while using it will be type cast )

 rect = new myRect();
    while(true)
    {    
       
       for(auto iter = verts.begin();iter != verts.end();++iter)
      {
        // getting co-ordinates of rectangle     
          QGraphicsRectItem* rectItem = rect->createRect(co-ordinates of rectangle);
          rect->_Ptr =  iter->_Ptr;  // trying to store _crossRefPtr  
      }

    }    

myRect.h

class myRect : public QGraphicsRectItem
{
   ........
  QGraphicsRectItem* createRect(QRectF& rect);       
  
}        
  

And when I will click on rectangle on scene through mouse I am doing like this:

if(_scene->selectedItems().count() != 0)
    {
        foreach(QGraphicsItem* currentItem, _scene->selectedItems())
        {
            QGraphicsRectItem* rItem = qgraphicsitem_cast<QGraphicsRectItem*>(currentItem);
            if(rItem)
            {
                myRect* r = reinterpret_cast<myRect*>(rItem);
                if(r)
                {
                    Instance (rectangle)
                    Instance* i = reinterpret_cast<Instance*>(r->_boostRefPtr); 
                    qDebug()<< i->Name();
                }
            }     
    

But aobve way is wrong. Getting run time errors ( Showing Verbose stack trace)
So the question is :

How to store pointer on QGraphicsItem so that, once they get selected, that pointer will be accessed ?


Solution

  • Use Qt's dynamic properties, check QObject::setProperty. It should do the trick.

    But AFAIC, I would have used a double QMap to associate directly <graph_node, QGraphicsItem> AND <QGraphicsItem, graph_node> - so you can search quickly for both associations, and both in O(log2(n)) complexity. You can store this either as a static part of your graph (better) or standalone (not the best idea). Obviously, if your graph is already in O(log2(n)), you don't need this map and you need only the <QGraphicsItem, graph_node> one.